簡體   English   中英

我可以將元組放入 python 的數組中嗎?

[英]Can I put a tuple into an array in python?

我想知道如何將元組放入數組中? 還是在數組中使用 arrays 來設計程序而不是在數組中使用元組更好? 請給我建議。 謝謝你

要記住的一件事是元組是不可變的。 這意味着一旦創建,您就無法就地修改它。 另一方面,列表是可變的——這意味着您可以就地添加元素、刪除元素和更改元素。 列表有額外的開銷,因此只有在需要修改值時才使用列表。

您可以創建一個元組列表:

>>> list_of_tuples = [(1,2),(3,4)]
>>> list_of_tuples
[(1, 2), (3, 4)]

或列表列表:

>>> list_of_lists = [[1, 2], [3, 4]]
>>> list_of_lists
[[1, 2], [3, 4]]

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

>>> list_of_lists[0][0] = 7
>>> list_of_lists
[[7, 2], [3, 4]]

但不是元組列表:

>>> 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

遍歷元組列表:

>>> for (x,y) in list_of_tuples:
...    print x,y
... 
1 2
3 4

如果你在談論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

如果您的意思是array ,則沒有 python array不支持元組。

a = [ ('b', i , "ff" ) for i in range(1,5)]  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM