元组/列表之间的区别是什么?它们的优点/缺点是什么?


当前回答

换句话说,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)
] 

其他回答

列表是可变的,元组是不可变的。 考虑一下这个例子。

a = ["1", "2", "ra", "sa"]    #list
b = ("1", "2", "ra", "sa")    #tuple

现在改变list和tuple的索引值。

a[2] = 1000
print a     #output : ['1', '2', 1000, 'sa']
b[2] = 1000
print b     #output : TypeError: 'tuple' object does not support item assignment.

因此证明下面的代码是无效的元组,因为我们试图更新一个元组,这是不允许的。

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

如果你去散步,你可以随时在(x,y)元组中记下你的坐标。

如果你想记录你的旅程,你可以每隔几秒钟将你的位置添加到一个列表中。

但你不能反过来做。

list的值可以随时更改,但元组的值不能更改。

优点和缺点取决于使用。如果你有这样一个你不想改变的数据,那么你应该使用tuple,否则list是最好的选择。

换句话说,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)
]