Python 中元组和列表有什么不同和相似之处?


列表和元组都被称为 Python 的序列数据类型。两种类型的对象都是用逗号分隔的项的集合,但并不一定属于同一种类型。

相似之处

两种类型的对象都可以进行连接、重复、索引和切片

>>> #list operations
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> #concatenation
>>> L3=L1+L2
>>> L3
[1, 2, 3, 4, 5, 6]
>>> #repetition
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> #indexing
>>> L3[4]
5
>>> #slicing
>>> L3[2:4]
[3, 4]


>>> #tuple operations
>>> T1=(1,2,3)
>>> T2=(4,5,6)
>>> #concatenation
>>> T3=T1+T2
>>> T3
(1, 2, 3, 4, 5, 6)
>>> #repetition
>>> T1*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> #indexing
>>> T3[4]
5
>>> #slicing
>>> T3[2:4]
(3, 4)

以下内置函数对于两种类型都是通用的

len() − 返回序列中的元素数量

>>> L1=[45,32,16,72,24]
>>> len(L1)
5
>>> T1=(45,32,16,72,24)
>>> len(T3)

max() − 返回值最大的元素。

>>> max(L1)
72
>>> max(T1)
72

min() − 返回值最小的元素。

>>> max(T1)
72
>>> min(L1)
16
>>> min(T1)
16

不同之处

列表对象是可变的。因此,可以向列表中添加、更新或删除一项。

>>> L1=[45,32,16,72,24]
>>> L1.append(56)
>>> L1
[45, 32, 16, 72, 24, 56]
>>> L1.insert(4,10) #insert 10 at 4th index
>>> L1
[45, 32, 16, 72, 10, 24, 56]
>>> L1.remove(16)
>>> L1
[45, 32, 72, 10, 24, 56]
>>> L1[2]=100 #update
>>> L1
[45, 32, 100, 10, 24, 56]

元组是不可变对象。任何尝试修改它的操作都会导致 AttributeError

T1.append(56)
AttributeError: 'tuple' object has no attribute 'append'
>>> T1.remove(16)
AttributeError: 'tuple' object has no attribute 'remove'
>>> T1[2]=100
TypeError: 'tuple' object does not support item assignment


更新日期:2020 年 2 月 20 日

818 次浏览

开启你的 职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.