新建

  1. a = ()
  2. print(type(a))
  3. # 输出
  4. # <class 'tuple'>

删除

元组中的元素值是不允许删除的,可以通过del删除整个元组

  1. a = (1, 3)
  2. del a

修改

  1. # 元组不允许以下方式直接修改
  2. a = (1, 3, 4)
  3. a[1] = 1
  4. # TypeError: 'tuple' object does not support item assignment

查找

  1. a = (1, 3, 3, 4, 55)
  2. # 查找
  3. print(a[1:3])
  4. # 输出
  5. # (3, 3)

内置方法

  1. # 获取元组个数
  2. len((a, b, c))
  3. # 新建元组
  4. (1, 3) + (4, 33)
  5. # 元组复制
  6. (3) * 3
  7. # 判断元组元素是否存在
  8. "a" in ("a", "b")
  9. #将可迭代系列转换为元组
  10. tuple(iterable)
  11. # 返回元组最大/最小值
  12. max((1, 3, 4))/min((3, 5, 6))

特性

元组是不可变的指的是元组所指向的内存中的内容不可变

具名元组

collections.namedtuple 保留元组的功能,外加允许为元组每个成员命名,通过名称访问成员

  1. from collections import namedtuple
  2. name = namedtuple('name_tuple', 'a, b, c, d')
  3. a = name(1, 2, 4, 4)
  4. print("a = %s" % a.a) # a = 1
  5. print("b = %s" % a.b) # b = 2
  6. name = namedtuple('name_tuple', ['a', 'b', 'c'])
  7. a= name(a=1, b=2, c=3)
  8. print("a = %s" % a.a) # a = 1
  9. print("a = %s" % a[0]) # a = 1
  10. print("b = %s" % a.b) # b = 2
  11. """通过typing和类型注解语法定义具名元组类型"""
  12. from typing import NamedTuple
  13. class Rectangle(NamedTuple):
  14. width: int
  15. height: int
  16. rect = Rectangle(width=10, height=10)
  17. print(rect) # Rectangle(width=10, height=10)
  18. print(rect.width) # 10

元组转字典:_asdict() 字典转元组:_make(iterable)

  1. from collections import namedtuple
  2. # 定义元组
  3. test_a = namedtuple('Poiint', ['x', 'y', 'z'])
  4. # 初始化元组
  5. a = test_a(1, 3, 4)
  6. # 具名元组转为字典
  7. print(a._asdict()) # OrderedDict([('x', 1), ('y', 3), ('z', 4)])
  8. # 字典转为元组
  9. test_b = {'x': 11, 'y': 22, 'z': 33}
  10. b = test_a._make(test_b)
  11. print(b) # Poiint(x='x', y='y', z='z')