1.基本元祖类型
元祖为不可变序列,你可以通过索引来访问该位置上的元素,你可以使用切片来获取指定范围内的元素,你同样可以拼接连个元祖成一个元祖但是不可修改元素
创建元祖可以使用tuple(...)函数,也可以用字面量
a = (1,3,4,5,6)
# 也可,a = 1,2,3,4,5,6 效果一样
在使用字面量表达式来创建元祖时,如果创建单个元素的元祖,必须在元素后面加上一个逗号
b = (1,) # b = 1,
a[1] # 返回 3
a[1:3] # 返回 (3,4)
a[1] = 2 # raise TypeError:object doesn't support item assignment
a * 2 # 返回(1,2,3,4,5,6,1,2,3,4,5,6)
a = a + (7,) # 返回(1,2,3,4,5,6,7)
2.Named tuple命名元祖
带有命名字段的元祖工厂函数collections.namedtuple(),我们可以在任何常规元祖使用的地方使用命名元祖, 并且命名元祖可以通过字段名来访问字段值,同时也可以通过索引位置来访问字段值。
举个简单的例子:
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)
实际应用中:
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
print(emp.name, emp.title)
import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print(emp.name, emp.title)
常用方法调用:
- 1.
classmethod somenamedtuple._make(iterable)
(类方法)
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
- 2.
somenamedtuple._asdict()
(实例方法)
>>> p = Point(x=11, y=22)
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])
- 3.
somenamedtuple._replace(**kwargs)
>>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)
- 4.
somenamedtuple._fields
(类属性)
>>> p._fields # view the field names
('x', 'y')
>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
要将字典转化为指定的元祖,我们可以使用一个技巧:
>>> d = {'x': 11, 'y': 22}
>>> Point(**d)
Point(x=11, y=22)