Python 元组
元组的定义 元组(tuple)是一种Python对象类型,元组也是一种序列
Python中的元组与列表类似,不同之处元组的元素不能修改
元组使用小括号,列表使用方括号
元组的创建,即在括号中添加元素,并使用逗号隔开
>>> a = 123,"aaa",["python","pass"]
>>> a
(123, 'aaa', ['python', 'pass'])
>>> type(a)
<type 'tuple'>
>>> print "I love %s,and I am a %s"%("Python","programmer")
I love Python,and I am a programmer
元组是一种序列,序列的基本操作 len() 、+、*、in、max()、min()、cmp()
元组与序列之间的转换
元组是不可修改的
>>> a =(1,2,3)
>>> id(a) #a与b两个元组进行对比,是两个不同的对象
44307080L
>>> b=(1,3,2)
>>> id(b)
48683696L
>>> a
(1, 2, 3)
>>> len(a) #计算长度
3
>>> b
(1, 3, 2)
>>> a + b #将两个元组连接在一起
(1, 2, 3, 1, 3, 2)
>>> a * 3 #将a元组重复3次
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> 3 in a #判断3这个元素是否在a这个元组中
True
>>> 4 in a #判断4这个元素是否在a这个元组中
False
>>> max(a) #计算元组a中的最大值
3
>>> min(a) #计算元组a中的最小值
1
>>> cmp(a,b) #比较元组a、b的大小
-1
>>> alst =list(a) #将元组转换为列表
>>> alst
[1, 2, 3]
>>> c =tuple(alst) #将列表转换为元组
>>> c
(1, 2, 3)
>>> a
(1, 2, 3)
>>> a.append(4) #向元组中追加元素,元组不可追加元素
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append' #元组没有属性append
>>> dir(tuple) #dir 查看元组,仅有count index
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
元组的索引和切片,与列表和字符串类似
元组中只包含一个元素时,需要在元素后面添加逗号
>>> a
(1, 2, 3)
>>> a[0] #通过索引值取出元素
1
>>> a[1]
2
>>> a[2]
3
>>> a[1:] #通过切片方式取出元素
(2, 3)
>>> a[0:2]
(1, 2)
>>> a[::-1] #将元组a反转
(3, 2, 1)
>>> alst[1]=100 #向alst列表中增加元素 alst[1]
>>> alst
[1, 100, 3]
>>> a[1]=100 #元组中不能通过此方式添加元素
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment 元组不支持修改
>>> temp =list(a) #将元组a转换成列表存于temp临时变量中
>>> temp[1]=100 #将100添加到列表temp索引位置为1的地方
>>> a =tuple(temp) #再将temp转为元组
>>> a #实现元组与列表之间的互转
(1, 100, 3)
>>> [1] #单独的[1]是一个列表
[1]
>>> type([1])
<type 'list'>
>>> type((1)) #单独(1)是一个整型
<type 'int'>
>>> type((1,)) #单独(1,)是一个元组, 元组中只包含一个元素时,需要在元素后面添加逗号
<type 'tuple'>
>>>
元组的count()和index()
>>> a
(1, 100, 3)
>>> b=a*3
>>> b
(1, 100, 3, 1, 100, 3, 1, 100, 3)
>>> b.count(1) #统计1出现的次数
3
>>> b.index(3) #计算3第一次出现的位置
2
元组的意义
元组比列表操作速度快
对数据“写保护” 因为元组不可修改
可用于字符串格式化中
可作为字典的key