列表list和元组tuple的区别

Python有两个非常相似的集合式的数据类型,分别是list和tuple,定义形式常见的说法是数组。

tuple通过小括号( )定义,定义后无法编辑元素内容(即不可变),而list通过中括号[ ]定义,其元素内容可以编辑(即可变),编辑动作包含删除pop( )、末尾追加append( )、插入insert( ).

可变的list

>>> name=['cong','rick','long']
>>> name[-2]     #等同于name[1]
'rick'
>>> name.append('tony')
>>> name.insert(0,'bob')      #在第一个位置即索引0处插入bob
>>> name.insert(2,'Jam')      
>>> name
['bob', 'cong', 'Jam', 'rick', 'long', 'tony']
>>> name.pop()      #删除最后的元素
'tony'
>>> name.pop(0)     #删除第一个元素
'bob'
>>> name
['cong', 'Jam', 'rick', 'long']

不可变的tuple

>>> month=('Jan','Feb','Mar')
>>> len(month)
3
>>> month
('Jan', 'Feb', 'Mar')
>>> month[0]
'Jan'
>>> month[-1]
'Mar'
>>> month.appnd('Apr')    #编辑元素内容会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'appnd'

若要编辑通过tuple定义的元素,可先转换为list再编辑:

>>> month_1=list(month)      #转换为list
>>> month_1
['Jan', 'Feb', 'Mar']
>>> month_1.append('Apr')    #可追加
>>> month_1
['Jan', 'Feb', 'Mar', 'Apr']         
>>> month
('Jan', 'Feb', 'Mar')
>>> month=tuple(month_1)     #转回tuple
>>> month
('Jan', 'Feb', 'Mar', 'Apr') 

做个 “可变的”tuple

>>> A= ('a', 'b', ['C', 'D'])
>>> A[2]
['C', 'D']
>>> len(A)
3
>>> A[2][0]
'C'
>>> A[2][0]='GG'
>>> A[2][0]='MM'
>>> A
('a', 'b', ['MM', 'D'])
>>> A[2][0]='GG'
>>> A[2][1]='MM'
>>> A
('a', 'b', ['GG', 'MM'])
>>> print(A[1])       #print()可省略
b
>>> A[2][0]
GG

猜你喜欢

转载自blog.51cto.com/firelong/2316119