新建
a = ()print(type(a))# 输出# <class 'tuple'>
删除
元组中的元素值是不允许删除的,可以通过del删除整个元组
a = (1, 3)del a
修改
# 元组不允许以下方式直接修改a = (1, 3, 4)a[1] = 1# TypeError: 'tuple' object does not support item assignment
查找
a = (1, 3, 3, 4, 55)# 查找print(a[1:3])# 输出# (3, 3)
内置方法
# 获取元组个数len((a, b, c))# 新建元组(1, 3) + (4, 33)# 元组复制(3) * 3# 判断元组元素是否存在"a" in ("a", "b")#将可迭代系列转换为元组tuple(iterable)# 返回元组最大/最小值max((1, 3, 4))/min((3, 5, 6))
特性
元组是不可变的指的是元组所指向的内存中的内容不可变
具名元组
collections.namedtuple 保留元组的功能,外加允许为元组每个成员命名,通过名称访问成员
from collections import namedtuplename = namedtuple('name_tuple', 'a, b, c, d')a = name(1, 2, 4, 4)print("a = %s" % a.a) # a = 1print("b = %s" % a.b) # b = 2name = namedtuple('name_tuple', ['a', 'b', 'c'])a= name(a=1, b=2, c=3)print("a = %s" % a.a) # a = 1print("a = %s" % a[0]) # a = 1print("b = %s" % a.b) # b = 2"""通过typing和类型注解语法定义具名元组类型"""from typing import NamedTupleclass Rectangle(NamedTuple):width: intheight: intrect = Rectangle(width=10, height=10)print(rect) # Rectangle(width=10, height=10)print(rect.width) # 10
元组转字典:_asdict() 字典转元组:_make(iterable)
from collections import namedtuple# 定义元组test_a = namedtuple('Poiint', ['x', 'y', 'z'])# 初始化元组a = test_a(1, 3, 4)# 具名元组转为字典print(a._asdict()) # OrderedDict([('x', 1), ('y', 3), ('z', 4)])# 字典转为元组test_b = {'x': 11, 'y': 22, 'z': 33}b = test_a._make(test_b)print(b) # Poiint(x='x', y='y', z='z')
