数据类型之元祖

元祖(tuple)是一种特殊的序列类型,官方叫做 Immutable Sequence Types,不可变序列。

元祖用圆括号表示,元素之间用逗号隔开,可包含任意数据类型。

空元祖

>>> a=()
>>> a
()
>>> type(a)
<class 'tuple'>

只有一个元素的元祖,这里比较特殊,需要在这个元素后面加一个逗号。

>>> a=(1,)
>>> a
(1,)
>>> type(a)
<class 'tuple'>

>>> b=(1)
>>> type(b)
<class 'int'>

看到区别了吧,所以记住这一点。

>>> dir(t)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

元祖也是序列,也支持索引和切片。

由于元祖是不可变的,所以元祖定义之后元祖中的元素不能重新赋值,亦没有append、pop等方法。

需要注意的是,元祖本身是不可变的,不能修改和删除元素。但是,元祖支持加法和乘法,返回一个新元祖。

a = (1, 2)
b = (3, 4)
print(a + b)
# (1, 2, 3, 4)

print(a * 2)
# (1, 2, 1, 2)

参考:https://docs.python.org/3/library/stdtypes.html#tuples

原文地址:https://www.cnblogs.com/keithtt/p/7628164.html