>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2
它们都是有效的吗?出于某种原因,你更喜欢哪一种?
发布于 2018-02-16 19:12:27
一个有趣的区别是:
lst=[1]
print lst // prints [1]
print type(lst) // prints <type 'list'>
notATuple=(1)
print notATuple // prints 1
print type(notATuple) // prints <type 'int'>
^^ instead of tuple(expected)
逗号必须包含在元组中,即使它只包含单个值。例如,用(1,)
代替(1)
。
发布于 2012-01-18 03:04:41
它们不是列表,它们是一个列表和一个元组。您可以在Python教程中阅读有关tuples的内容。虽然你可以改变列表,但这对于元组是不可能的。
In [1]: x = (1, 2)
In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment
发布于 2012-01-18 03:04:32
第一个是一个列表,第二个是一个元组。列表是可变的,元组不是。
请看一下本教程的Data Structures部分和文档的Sequence Types部分。
https://stackoverflow.com/questions/8900166
复制相似问题