元组

元组是任意对象的有序、不可变序列,通常用于储存异构数据的集合,或是同构数据的不可变序列。除了是不可变的,元组在其他方面和列表基本相同。元组实现了所有通用的序列操作。

创建元组#

可通过圆括号来构建列表,圆括号内的各个对象使用逗号 , 分割。如下所示:

    pets = ('dog', 'cat', 'rabbit', 'fish')
    coordinate = (23.4, 35.6, 67.8)
    mixed_tuple = ('dog', 4, False, ['a', 'c'])
    
    print(pets, type(pets))  # ('dog', 'cat', 'rabbit', 'fish') <class 'tuple'>
    print(coordinate, type(coordinate))  # (23.4, 35.6, 67.8) <class 'tuple'>
    print(mixed_tuple, type(mixed_tuple))  # ('dog', 4, False, ['a', 'c']) <class 'tuple'>

尽管在打印输出时,元组总由圆括号标注,但在输入时,圆括号是可有可无的。如下所示:

    tuple1 = 1, 2, 3, 'c'

    print(tuple1, type(tuple1))  # (1, 2, 3, 'c') <class 'tuple'>

请注意决定生成元组的其实是逗号而不是圆括号。圆括号只是可选的,生成空元组或需要避免语法歧义的情况除外。例如,f(a, b, c) 是在调用函数时传入三个参数,而 f((a, b, c)) 则是在调用函数时传输一个三元组参数。

不包含任何元素的元组称为空元组,用 () 表示。下面创建一个名称为 empty_tuple 的空元组:

    empty_tuple = ()

只包含一个元素的元组是单元组,其表示形式为:

    singleton_tuple1 = 1,
    singleton_tuple2 = (1,)

    print(singleton_tuple1, type(singleton_tuple1))  # (1,) <class 'tuple'>

也可以使用内置的 tuple() 函数(这是元组类型的构造器)从一个可迭代对象创建元组:

    tuple1 = tuple( [1, 2, 3] )  # (1, 2, 3)
    tuple2 = tuple( (1, 2, 3) )  # (1, 2, 3)
    tuple3 = tuple('abcd')  # ('a', 'b', 'c', 'd')
    tuple4 = tuple(range(3, 13, 3))  # (3, 6, 9, 12)
    tuple5 = tuple( {'mammal', 'bird', 'reptile', 'fish'} )  # ('reptile', 'bird', 'mammal', 'fish')
    tuple6 = tuple()  # 空元组 ()

打包和解包#

形如 t = 33, 'hello', True 的语句称为元组打包,这将值 33, 'hello'True 一起打包进元组。元组打包的逆操作为:

    x, y, z = t

该操作被称为序列解包,其右侧可以是元组、列表、集合或字典这些容器类型。如下所示:

    t = [33, 'hello', True]  # 对列表解包
    x, y, z = t
    print(x, y, z)  # 33 hello True
    t = {33, 'hello', True}  # 对集合解包
    x, y, z = t
    print(x, y, z)  # 33 hello True
    days = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday'}  # 对字典解包
    x, y, z = days
    print(x, y, z)  # 1 2 3

访问元组#

读取、遍历元组的各种操作与列表类似,不再赘述。

元组与列表的区别#

元组与列表很像,但两者使用场景不同,用途也不同。

元组是不可变的(immutable),一般可包含异质元素序列,常通过解包或索引访问。列表是可变的(mutable),列表元素一般为同质类型,常通过迭代访问。元组没有实现可变序列的操作,如添加或删除元素等。

元组比列表的访问和处理速度更快,所以当只是需要对其中的元素进行访问,而不进行任何修改时,建议使用元组。

列表不能作为字典的键,而元组可以。

列表集合