元组——tuple

元组——tuple

  • 一个有序的元素组成的集合
  • 使用小括号 () 表示
  • 元组是不可变对象

元组的定义 初始化

  • 定义
    • tuple() -> empty tuple
    • tuple(iterable) -> tuple initialized from iterable’s items
t = tuple() # 工厂方法
> t = ()

t = ()
> t = ()

t = tuple(range(1, 7, 2)) # iterable
> t = (1, 3, 5)

t = (2, 4, 6, 3, 4, 2)
> t = (2, 4, 6, 3, 4, 2)

t = (1,) # 一个元素元组的定义,注意有个逗号
> t = (1,)

t = (1,) * 5
> t = (1, 1, 1, 1, 1)

t = (1, 2, 3) * 6
> t = (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

元组元素的访问

  • 支持索引(下标)
  • 正索引:从左至右,从 0 开始,为列表中每一个元素编号
  • 负索引:从右至左,从 -1 开始
  • 正负索引不可以越界,否则引发异常 IndexError
  • 元素通过索引访问
    • tuple[index] ,index 就是索引,使用中括号 [ ] 访问

元组查询

  • index(value, [start, [stop]])
    • 通过值 value ,从指定区间查找列表内的元素是否匹配
    • 匹配第一个就立即返回索引
    • 匹配不到,抛出异常 ValueError
  • count(value)
    • 返回列表中匹配 value 的次数
  • 时间复杂度
    • index 和 count 方法都是 O(n)
    • 随着列表数据规模的增大,而效率下降
  • len(tuple)
    • 返回元组里面元素的个数

元组其他操作

元组是只读的,所以增、删、改方法都没有


命名元组 namedtuple

  • namedtuple(typename, field_names, verbose = False, rename = False)
    • 命名元组,返回一个元组的子类,并定义了字段
    • field_names 可以是空白符或逗号分割的字段的字符串,可以是字段的列表
from collections import namedtuple

Point = namedtuple('_Point',['x','y']) # Point为返回的类
p = Point(11,22)
print(p)
> _Point(x=11, y=22)

Student = namedtuple('Student','name age')
tom = Student('tom',20)
jerry = Student('jerry',18)
print(tom.name,jerry.age)
> tom 18

tom.age = 100 # 可以吗
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-d0243da30d77> in <module>
----> 1 tom.age = 100

AttributeError: can't set attribute

如同元组一样,命名元组的属性们的值不可变

原文地址:https://www.cnblogs.com/d1anlong/p/11868782.html