gpt4 book ai didi

python - python元组可以修改吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:10 29 4
gpt4 key购买 nike

我正在读取和解析一些数据。基本上,数据是一堆整数和字符串,所以我不能只使用一个列表来存储数据。每组数据中都有一定数量的项目,但有时会丢失一些项目。这是我的。

users = [] # list of objects I'll be creating

# this all gets looped. snipped for brevity
data = "id", "gender", -1 # my main tuple that I will create my object with
words = line.split()
index = 0
data[0] = words[index]
index += 1
if words[index] == "m" or words[index] == "f":
data[1] = words[index]
index += 1
else:
data[1] = "missing"

if words[index].isdigit():
data[2] = words[index]
index += 1

users.append(User(data))

问题是你似乎不能直接赋值给元组(比如data[1] = "missing"),那么这应该如何以pythonic方式赋值呢?

最佳答案

Python 元组是不可变的。来自documentation :

Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple (you can simulate much of the same effect with slicing and concatenation, though). It is also possible to create tuples which contain mutable objects, such as lists.

这是将它们与列表区分开来的主要因素。这很好地引出了一种可能的解决方案:使用列表代替元组:

data = ["id", "gender", -1]

关于python - python元组可以修改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9710093/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com