元组/列表之间的区别是什么?它们的优点/缺点是什么?
当前回答
除了元组是不可变的之外,还有一个语义上的区别应该指导它们的使用。元组是异构数据结构(即,它们的条目有不同的含义),而列表是同构序列。元组有结构,列表有顺序。
使用这种区别可以使代码更加明确和易于理解。
一个例子是用页码和行号对来引用书中的位置,例如:
my_location = (42, 11) # page number, line number
然后,您可以使用它作为字典中的键来存储关于位置的注释。另一方面,列表可用于存储多个位置。自然,人们可能想要从列表中添加或删除位置,所以列表是可变的是有道理的。另一方面,从现有位置添加或删除项没有意义——因此元组是不可变的。
在某些情况下,您可能希望更改现有位置元组中的项,例如在遍历页面的行时。但是元组不可变性迫使您为每个新值创建一个新的位置元组。从表面上看,这似乎不太方便,但像这样使用不可变数据是值类型和函数式编程技术的基础,具有很大的优势。
关于这个问题有一些有趣的文章。“Python元组不仅仅是常量列表”或“理解Python中的元组与列表”。Python官方文档也提到了这一点
元组是不可变的,通常包含异构序列…
在像Haskell这样的静态类型语言中,元组中的值通常具有不同的类型,并且元组的长度必须是固定的。在列表中,所有值都具有相同的类型,长度也不是固定的。所以区别非常明显。
最后是Python中的namedtuple,这是有意义的,因为tuple已经被认为具有结构。这强调了元组是类和实例的轻量级替代品的观点。
其他回答
这是一个Python列表的例子:
my_list = [0,1,2,3,4]
top_rock_list = ["Bohemian Rhapsody","Kashmir","Sweet Emotion", "Fortunate Son"]
这是一个Python元组的例子:
my_tuple = (a,b,c,d,e)
celebrity_tuple = ("John", "Wayne", 90210, "Actor", "Male", "Dead")
Python lists and tuples are similar in that they both are ordered collections of values. Besides the shallow difference that lists are created using brackets "[ ... , ... ]" and tuples using parentheses "( ... , ... )", the core technical "hard coded in Python syntax" difference between them is that the elements of a particular tuple are immutable whereas lists are mutable (...so only tuples are hashable and can be used as dictionary/hash keys!). This gives rise to differences in how they can or can't be used (enforced a priori by syntax) and differences in how people choose to use them (encouraged as 'best practices,' a posteriori, this is what smart programers do). The main difference a posteriori in differentiating when tuples are used versus when lists are used lies in what meaning people give to the order of elements.
对于元组,“order”只是表示用于保存信息的特定“结构”。在第一个字段中找到的值可以很容易地切换到第二个字段中,因为每个字段提供跨越两个不同维度或尺度的值。它们为不同类型的问题提供答案,通常的形式是:对于给定的对象/主题,它的属性是什么?对象/主题保持不变,属性不同。
对于列表,“order”表示序列或方向性。第二个元素必须在第一个元素之后,因为它的位置是基于一个特定的和公共的比例或维度。这些元素被视为一个整体,主要是为一个典型的形式的问题提供答案,对于一个给定的属性,这些对象/主题如何比较?属性保持不变,对象/主语不同。
在流行文化和程序员中,有无数的人不符合这些差异,也有无数的人可能会用沙拉叉吃主菜。在一天结束的时候,这很好,两者通常都可以完成工作。
总结一些更精细的细节
相似之处:
Duplicates - Both tuples and lists allow for duplicates Indexing, Selecting, & Slicing - Both tuples and lists index using integer values found within brackets. So, if you want the first 3 values of a given list or tuple, the syntax would be the same: >>> my_list[0:3] [0,1,2] >>> my_tuple[0:3] [a,b,c] Comparing & Sorting - Two tuples or two lists are both compared by their first element, and if there is a tie, then by the second element, and so on. No further attention is paid to subsequent elements after earlier elements show a difference. >>> [0,2,0,0,0,0]>[0,0,0,0,0,500] True >>> (0,2,0,0,0,0)>(0,0,0,0,0,500) True
区别:-根据定义,是先验的
Syntax - Lists use [], tuples use () Mutability - Elements in a given list are mutable, elements in a given tuple are NOT mutable. # Lists are mutable: >>> top_rock_list ['Bohemian Rhapsody', 'Kashmir', 'Sweet Emotion', 'Fortunate Son'] >>> top_rock_list[1] 'Kashmir' >>> top_rock_list[1] = "Stairway to Heaven" >>> top_rock_list ['Bohemian Rhapsody', 'Stairway to Heaven', 'Sweet Emotion', 'Fortunate Son'] # Tuples are NOT mutable: >>> celebrity_tuple ('John', 'Wayne', 90210, 'Actor', 'Male', 'Dead') >>> celebrity_tuple[5] 'Dead' >>> celebrity_tuple[5]="Alive" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment Hashtables (Dictionaries) - As hashtables (dictionaries) require that its keys are hashable and therefore immutable, only tuples can act as dictionary keys, not lists. #Lists CAN'T act as keys for hashtables(dictionaries) >>> my_dict = {[a,b,c]:"some value"} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' #Tuples CAN act as keys for hashtables(dictionaries) >>> my_dict = {("John","Wayne"): 90210} >>> my_dict {('John', 'Wayne'): 90210}
差异——用法上的后验
Homo vs. Heterogeneity of Elements - Generally list objects are homogenous and tuple objects are heterogeneous. That is, lists are used for objects/subjects of the same type (like all presidential candidates, or all songs, or all runners) whereas although it's not forced by), whereas tuples are more for heterogenous objects. Looping vs. Structures - Although both allow for looping (for x in my_list...), it only really makes sense to do it for a list. Tuples are more appropriate for structuring and presenting information (%s %s residing in %s is an %s and presently %s % ("John","Wayne",90210, "Actor","Dead"))
如果你去散步,你可以随时在(x,y)元组中记下你的坐标。
如果你想记录你的旅程,你可以每隔几秒钟将你的位置添加到一个列表中。
但你不能反过来做。
最重要的区别是时间!当你不想改变列表里面的数据时最好使用元组!下面是为什么使用tuple的例子!
import timeit
print(timeit.timeit(stmt='[1,2,3,4,5,6,7,8,9,10]', number=1000000)) #created list
print(timeit.timeit(stmt='(1,2,3,4,5,6,7,8,9,10)', number=1000000)) # created tuple
在本例中,我们执行了这两条语句100万次
输出:
0.136621
0.013722200000000018
任何人都能清楚地注意到时差。
list和tuple的区别
Literal someTuple = (1,2) someList = [1,2] Size a = tuple(range(1000)) b = list(range(1000)) a.__sizeof__() # 8024 b.__sizeof__() # 9088 Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements. Permitted operations b = [1,2] b[0] = 3 # [3, 2] a = (1,2) a[0] = 3 # Error That also means that you can't delete an element or sort a tuple. However, you could add a new element to both list and tuple with the only difference that since the tuple is immutable, you are not really adding an element but you are creating a new tuple, so the id of will change a = (1,2) b = [1,2] id(a) # 140230916716520 id(b) # 748527696 a += (3,) # (1, 2, 3) b += [3] # [1, 2, 3] id(a) # 140230916878160 id(b) # 748527696 Usage As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used. a = (1,2) b = [1,2] c = {a: 1} # OK c = {b: 1} # Error
除了元组是不可变的之外,还有一个语义上的区别应该指导它们的使用。元组是异构数据结构(即,它们的条目有不同的含义),而列表是同构序列。元组有结构,列表有顺序。
使用这种区别可以使代码更加明确和易于理解。
一个例子是用页码和行号对来引用书中的位置,例如:
my_location = (42, 11) # page number, line number
然后,您可以使用它作为字典中的键来存储关于位置的注释。另一方面,列表可用于存储多个位置。自然,人们可能想要从列表中添加或删除位置,所以列表是可变的是有道理的。另一方面,从现有位置添加或删除项没有意义——因此元组是不可变的。
在某些情况下,您可能希望更改现有位置元组中的项,例如在遍历页面的行时。但是元组不可变性迫使您为每个新值创建一个新的位置元组。从表面上看,这似乎不太方便,但像这样使用不可变数据是值类型和函数式编程技术的基础,具有很大的优势。
关于这个问题有一些有趣的文章。“Python元组不仅仅是常量列表”或“理解Python中的元组与列表”。Python官方文档也提到了这一点
元组是不可变的,通常包含异构序列…
在像Haskell这样的静态类型语言中,元组中的值通常具有不同的类型,并且元组的长度必须是固定的。在列表中,所有值都具有相同的类型,长度也不是固定的。所以区别非常明显。
最后是Python中的namedtuple,这是有意义的,因为tuple已经被认为具有结构。这强调了元组是类和实例的轻量级替代品的观点。