我可以在python中将元组放入数组中吗?

iCe*_*ezz 18 python arrays tuples

我想知道如何将元组放入数组中?或者更好的是在数组中使用数组来设计程序而不是数组中的元组?请指教.谢谢

jte*_*ace 23

要记住的一件事是元组是不可变的.这意味着一旦创建,您就无法就地修改它.一个列表,在另一方面,是可变的-这意味着你可以添加元素,删除元素,并更改就地元素.列表有额外的开销,因此只有在需要修改值时才使用列表.

您可以创建元组列表:

>>> list_of_tuples = [(1,2),(3,4)]
>>> list_of_tuples
[(1, 2), (3, 4)]
Run Code Online (Sandbox Code Playgroud)

或列表清单:

>>> list_of_lists = [[1, 2], [3, 4]]
>>> list_of_lists
[[1, 2], [3, 4]]
Run Code Online (Sandbox Code Playgroud)

不同之处在于您可以修改列表列表中的元素:

>>> list_of_lists[0][0] = 7
>>> list_of_lists
[[7, 2], [3, 4]]
Run Code Online (Sandbox Code Playgroud)

但不是元组列表:

>>> list_of_tuples[0][0] = 7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)

迭代元组列表:

>>> for (x,y) in list_of_tuples:
...    print x,y
... 
1 2
3 4
Run Code Online (Sandbox Code Playgroud)


Kar*_*ath 8

如果你在谈论list,你可以把任何东西,甚至不同的类型:

l=[10,(10,11,12),20,"test"]

l[0] = (1,2,3)
l.append((4,5))
l.extend((21,22)) #this one adds each element from the tuple
Run Code Online (Sandbox Code Playgroud)

如果你的意思是array,没有python 数组不支持元组.