元组(定值表)
用来存储固定不变的值表,有序序列。
创建元组:
1.字面量的方式
(x1,x2,...)
x1,x2,..
如果只有一个元素,在该元素后面加上,
>>> t1 = (1,2,3,4)
>>> t1
(1, 2, 3, 4)
>>> t2 = 1,2,3,4
>>> t2
(1, 2, 3, 4)
>>> t3 =()
>>> t3
()
>>> t4 = 1,
>>> t4
(1,)
>>> t5= (1,)
>>> t5
(1,)
2.对象方式
>>> t6 = tuple([1,2,3,4,5,6])
>>> t6
(1, 2, 3, 4, 5, 6)
>>> t7 = tuple("abcde")
>>> t7
('a', 'b', 'c', 'd', 'e')
3.推导式
>>> t9 = tuple(range(8))
>>> t9
(0, 1, 2, 3, 4, 5, 6, 7)
>>> t10 = tuple([2*x for x in range(1,5)])
>>> t10
(2, 4, 6, 8)
元组的值不能改?:
>>> a = tuple("abc")
>>> b=a,[1,2,3]
>>> b
(('a', 'b', 'c'), [1, 2, 3])
>>> b[1][1]=5
>>> b
(('a', 'b', 'c'), [1, 5, 3])
操作
>>> t1=(1,2,3,4,5)
>>> t1
(1, 2, 3, 4, 5)
>>> t1[2]
3
>>> for x in t1:
print(x,end=" ")
1 2 3 4 5
>>> len(t1)
5
>>> min(t1)
1
>>> max(t1)
5
>>> sum(t1)
15
>>> t1[::]
(1, 2, 3, 4, 5)
>>> t1[1:2]
(2,)
>>> t1[::2]
(1, 3, 5)
>>> t2=(1,2,3)
>>> t1+t2
(1, 2, 3, 4, 5, 1, 2, 3)
>>> t1*t2
成员关系运算:
in
not in
>>> t1.index(2)
1
>>> t1.count(1)
1
其他操作
>>> for x in 3,2,3.12:
print(x)
3
2
3.12
>>> t1 = (5,3,2,1,)
>>> t1
(5, 3, 2, 1)
>>> sorted(t1)
[1, 2, 3, 5]
拆分:
>>> data
(1100, 'abc', (1, 2, 3))
>>> sid,name,score=data
>>> sid
1100
>>> name
'abc'
>>> score
(1, 2, 3)
拆分
>>> first,middle,last = (1,2,3,4,5,6,4,7,8,9)
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
first,middle,last = (1,2,3,4,5,6,4,7,8,9)
ValueError: too many values to unpack (expected 3)
>>> first,*middle,last = (1,2,3,4,5,6,4,7,8,9)
>>> first
1
>>> middle
[2, 3, 4, 5, 6, 4, 7, 8]
>>> last
9
Eg:
去掉最高和最低分,求均值
>>> first,*middle,last = sorted((1,58,5,58,45,87))
>>> sum(middle)/len(middle)
41.5
临时变量
>>> _,b,_=(1,2,3)
>>> _
3
>>> b
2
列表与元组的相互转换
>>> t1 = (1,2,3,4,5)
>>> list1 = list(t1)
>>> list1
[1, 2, 3, 4, 5]
>>> t2 = tuple(list1)
>>> t2
(1, 2, 3, 4, 5)