元组/列表之间的区别是什么?它们的优点/缺点是什么?
当前回答
列表是同构序列,而元组是异构数据结构。
其他回答
List是可变的,tuples是不可变的。可变和不可变之间的主要区别是当您试图追加一个项时内存的使用。
当你创建一个变量时,一些固定的内存被分配给变量。如果它是一个列表,则分配的内存比实际使用的要多。例如,如果当前内存分配是100个字节,当你想追加第101个字节时,可能会再分配100个字节(在这种情况下总共是200个字节)。
然而,如果你知道你不经常添加新元素,那么你应该使用元组。Tuples精确地分配所需的内存大小,从而节省内存,特别是当您使用大块内存时。
这是一个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"))
首先,它们都是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还可能导致别名错误(两条不同的路径 指向同一对象)。
前面已经提到,这种差异主要是语义上的:人们期望元组和列表表示不同的信息。但这不仅仅是一个指导方针;一些库实际上根据传递的内容表现不同。以NumPy为例(复制自另一篇文章,我要求更多的例子):
>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
[3, 4, 5]])
关键是,虽然NumPy可能不是标准库的一部分,但它是一个主要的Python库,在NumPy中,列表和元组是完全不同的东西。
换句话说,TUPLES用于存储一组元素,其中组的内容/成员不会改变,而list用于存储一组元素,其中组的成员可以改变。
例如,如果我想在一个变量中存储我的网络IP,最好使用一个元组,因为IP是固定的。my_ip =('192.168.0.15', 33,60)。但是,如果我想存储一组未来6个月我将访问的地方的IP,那么我应该使用LIST,因为我会不断更新和添加新的IP到组中。像这样
places_to_visit = [
('192.168.0.15', 33, 60),
('192.168.0.22', 34, 60),
('192.168.0.1', 34, 60),
('192.168.0.2', 34, 60),
('192.168.0.8', 34, 60),
('192.168.0.11', 34, 60)
]
推荐文章
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 将Set<T>转换为List<T>的最简洁的方法
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- 在javascript中从平面数组构建树数组
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴