码迷,mamicode.com
首页 > 其他好文 > 详细

列表list和元组tuple的区别

时间:2018-11-13 00:22:20      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:mos   rac   cal   形式   位置   apr   定义   列表   lin   

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

列表list和元组tuple的区别

标签:mos   rac   cal   形式   位置   apr   定义   列表   lin   

原文地址:http://blog.51cto.com/firelong/2316119

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!