元组/列表之间的区别是什么?它们的优点/缺点是什么?
当前回答
首先,它们都是Python中的非标量对象(也称为复合对象)。
元组,有序的元素序列(可以包含任何没有混叠问题的对象) 不可变(tuple, int, float, str) 使用+进行连接(当然会创建一个全新的元组) 索引 切片 Singleton(3,) # ->(3)而不是(3)# -> 3 List(其他语言中的数组),值的有序序列 可变的 单例[3] 克隆new_array = origin_array[:] 列表推导式[x**2 for x in range(1,7)]给出 [1,4,9,16,25,36](不可读)
使用list还可能导致别名错误(两条不同的路径 指向同一对象)。
其他回答
列表是可变的;元组不是。
从docs.python.org/2/tutorial/datastructures.html
元组是不可变的,通常包含的异构序列 通过解包访问的元素(参见本节后面的内容) 或者索引(在命名元组的情况下甚至通过属性)。列表 是可变的,它们的元素通常是同质的和 通过遍历列表来访问。
正如人们已经提到的区别,我将写一下为什么是元组。
为什么首选元组?
小元组的分配优化 为了减少内存碎片和加快分配速度,Python重用旧元组。如果一个 元组不再需要,并且只有少于20个项而不是删除 Python会永久地将它移到一个空闲列表中。 一个空闲列表被分为20个组,每个组代表一个 长度为n的元组列表,从0到20。每组都可以储存 到2000个元组。第一个(零)组只包含一个元素和 表示空元组。
>>> a = (1,2,3)
>>> id(a)
4427578104
>>> del a
>>> b = (1,2,4)
>>> id(b)
4427578104
在上面的例子中,我们可以看到a和b有相同的id。这是 因为我们立即占用了一个被破坏的元组 空闲列表。 列表的分配优化 由于列表可以被修改,Python不会像元组那样使用相同的优化方法。然而, Python列表也有一个free列表,但它只用于空列表 对象。如果一个空列表被GC删除或收集,它可以被删除 以后重用。
>>> a = []
>>> id(a)
4465566792
>>> del a
>>> b = []
>>> id(b)
4465566792
来源:https://rushter.com/blog/python-lists-and-tuples/
为什么元组比列表更高效?- > https://stackoverflow.com/a/22140115
关键的区别是元组是不可变的。这意味着一旦创建了元组,就不能更改其中的值。
因此,如果您需要更改值,请使用List。
元组的好处:
性能略有改善。 元组是不可变的,可以用作字典中的键。 如果你不能改变它,其他人也不能,也就是说你不需要担心任何API函数等改变你的元组没有被要求。
正如人们已经在这里回答的那样,元组是不可变的,而列表是可变的,但是使用元组有一个重要的方面我们必须记住
如果元组中包含列表或字典,即使元组本身是不可变的,也可以更改这些列表或字典。
例如,假设我们有一个元组,其中包含一个列表和一个字典为
my_tuple = (10,20,30,[40,50],{ 'a' : 10})
我们可以将列表的内容更改为
my_tuple[3][0] = 400
my_tuple[3][1] = 500
new tuple看起来像什么
(10, 20, 30, [400, 500], {'a': 10})
我们还可以更改tuple as内的字典
my_tuple[4]['a'] = 500
这将使整个元组看起来像
(10, 20, 30, [400, 500], {'a': 500})
发生这种情况是因为list和dictionary是对象,这些对象没有改变,但它所指向的内容。
因此,元组保持不变,没有任何异常
这是一个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"))
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象