Python tuple - zhongjiajie/zhongjiajie.github.com GitHub Wiki

python-tuple

tuple和list看起来非常类似,但是他们有明显不同的使用情况和目的

  • tuple是不可变对象,通常用来存放异构数据,然后通过unpack或者index来访问里面的内容,或者通过collections.nametuple的属性来访问
  • list是可变对象,通常存放同类型的数据,然后通过遍历的方式访问元素
# 一般tuple的定义和赋值
t = 12345, 54321, 'hello!' # (12345, 54321, 'hello!')
t[0]  # 12345
u = t, (1, 2, 3, 4, 5)     # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# tuple 是不可变对象
t[0] = 8888     # 报错tuple object does not support item assignment
v = ([1, 2, 3], [3, 2, 1])  # 但是不可变对象的tuple可以包含可变对象,比如list

# 声明空 tuple 或者 只有一个元素的 tuple
empty = ()  # 直接用括号括起来
singleton = 'hello',  # 声明一个元素的tuple,注意最后的逗号, 或者可以 singleton = ('hello',)
  • 序列解包,将右侧序列的值解包到左侧多个变量,需要左侧的变量和右侧的一样多: t = (1, 'zhongjiajie', 23); id, name, age = t
⚠️ **GitHub.com Fallback** ⚠️