元组tuple
- 一个有序的元素组成的集合
- 使用小括号()表示
- 元组是不可变对象(所以如果创建一个空的元组tuple(),是不能变的 也就没多大用了…)
- 元组是只读的,所以增改删方法都没有
- 定义:
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable’s items
元组元素的访问
- 支持索引(下标)
- 正索引:从左至右,从0开始
- 负索引:从右至左,从-1开始
- 正负索引不可越界,否则引发IndexError
- 元组通过索引访问:tuple[index]
元祖查询
- index(value,[start,[stop]])
通过值value,从指定区间查找列表内的元素是否匹配
匹配第一个就立即返回索引
匹配不到,抛出异常ValueError - count(vaule)
返回列表中匹配value的次数 - 时间复杂度
index和count方法都是O(n)
随着列表数据规模的增大而效率下降 - len(tuple)
返回元素个数
命名元组(named tuple)
- 帮助文档中,查阅namedtuple,有使用例程
- namedtuple(typename,field_names,verbose= False,rename= False)
^ 命名元组,返回一个元组的子类,并定义了字段
^field_names可以是空格或逗号分隔的字段的字符串,可以是字段的列表
>>> from collections import namedtuple
>>> Point = namedtuple('_Point',['x','y'])
>>> p = Point(11,22)
>>> p
_Point(x=11, y=22)
>>> Student = namedtuple('Student','name age')
>>> tom = Student('tom',20)
>>> jerry = Student('jerry',18)
>>> tom.name
'tom'
>>> tom.age
20
>>> tom
Student(name='tom', age=20)
>>> m1 = Point(4,8)
>>> m1
_Point(x=4, y=8)
>>> m2 = Student('eee',99)
>>> m2
Student(name='eee', age=99)
>>> m2.age
99
>>> m1.x
4
>>> m2.x
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
m2.x
AttributeError: 'Student' object has no attribute 'x'
>>> m1+m2
(4, 8, 'eee', 99)
>>> m1.(x+y)
SyntaxError: invalid syntax
>>> m1.x+m1.y
12