元组是python序列中的一种,一旦创建不可更改。
本篇总结主要包括:元组创建、索引、排序、其他(最大值、最小值、求和)

元组创建

元组创建有两种方法:一种是定义;一种是通过tuple进行构建。

  1. >>> tuple1 = (2,3, 4) #元组定义式
  2. >>> tuple1
  3. (2, 3, 4)
  4. >>> a = tuple(x for x in range(1, 5)) #生成器推倒式
  5. >>> a
  6. (1, 2, 3, 4)

元组索引

  1. >>> a
  2. (1, 2, 3, 4)
  3. >>> a[0]
  4. 1
  5. >>> a[0::2]
  6. (1, 3)
  7. >>>

元组排序

可以使用内置函数sorted()进行排序操作,元组无sort()函数,但使用sorted()返回值为列表。

  1. >>> a
  2. (1, 2, 3, 4)
  3. >>> sorted(a)
  4. [1, 2, 3, 4]

其他

最值及求和

  1. >>> a
  2. (1, 2, 3, 4)
  3. >>> max(a)
  4. 4
  5. >>> min(a)
  6. 1
  7. >>> sum(a)
  8. 10

zip函数

生成器推导式建立元组

  1. >>> text = (x*x for x in range(5))
  2. >>> text.__next__
  3. <method-wrapper '__next__' of generator object at 0x0000024FB4278D60>
  4. >>> text.__next__()
  5. 0
  6. >>> text.__next__()
  7. 1
  8. >>> text.__next__()
  9. 4
  10. >>> text.__next__()
  11. 9
  12. >>> text.__next__()
  13. 16
  14. >>> text.__next__()
  15. Traceback (most recent call last):
  16. File "<pyshell#15>", line 1, in <module>
  17. text.__next__()
  18. StopIteration