元组tuple
- 一个有序的元素组成的集合
- 使用()表示
- 元组是不可变对象
元组的定义初始化
- 定义
- tuple() —> empty tuple # 因元组不可变,因此这种创建方法无意义
- tuple(iterable) —>返回元组的可迭代对象
t = tuple(range(1,7,2))
t = (1,2,3)*5
元组元素的访问
- 支持索引访问
- 正索引,从左至右,从0开始
- 负索引,从右至左,从-1开始
- 不可超界,会引发IndexError
- t[index]
元组查询
- index(value,[start, [stop]])
- 通过值,从指定区间查找元组内的元素是否匹配
- 匹配第一个返回索引
- 匹配不到,抛出异常ValueError
- count(value)
- 时间复杂度
- index和count方法都是O(n)
- 随着元组数据规模增大, 效率降低
- len(tuple)
命名元组namedtuple
- namedtuple(typename, field_names. verbose=False, rename=False)
- 命名元组,返回一个元组的子类,并定义了字段
- field_names可以是空格或逗号分隔的字段的字符串
from collections import namedtuple
Point = namedtuple(‘P‘, [‘x‘,‘y‘])
In [3]: p = Point(11,22)
In [4]: p
Out[4]: p(x=11, y=22)
In [5]: p.x
Out[5]: 11
In [6]: p.x + p.y
Out[6]: 33
Student = namedtuple(‘Student‘, ‘name age‘)
tom = Student(‘tom‘, 20)
jerry = Student(‘jerry‘, 18)
tom.name
Python中的tuple元祖
原文:https://www.cnblogs.com/larry-yu/p/15009848.html