元组是python序列中的一种,一旦创建不可更改。
本篇总结主要包括:元组创建、索引、排序、其他(最大值、最小值、求和)
元组创建
元组创建有两种方法:一种是定义;一种是通过tuple进行构建。
>>> tuple1 = (2,3, 4) #元组定义式
>>> tuple1
(2, 3, 4)
>>> a = tuple(x for x in range(1, 5)) #生成器推倒式
>>> a
(1, 2, 3, 4)
元组索引
>>> a
(1, 2, 3, 4)
>>> a[0]
1
>>> a[0::2]
(1, 3)
>>>
元组排序
可以使用内置函数sorted()进行排序操作,元组无sort()函数,但使用sorted()返回值为列表。
>>> a
(1, 2, 3, 4)
>>> sorted(a)
[1, 2, 3, 4]
其他
最值及求和
>>> a
(1, 2, 3, 4)
>>> max(a)
4
>>> min(a)
1
>>> sum(a)
10
zip函数
生成器推导式建立元组
>>> text = (x*x for x in range(5))
>>> text.__next__
<method-wrapper '__next__' of generator object at 0x0000024FB4278D60>
>>> text.__next__()
0
>>> text.__next__()
1
>>> text.__next__()
4
>>> text.__next__()
9
>>> text.__next__()
16
>>> text.__next__()
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
text.__next__()
StopIteration