Python-Collections模块之NameTuple

namedtuple : 可以创建包含名称的tuple

一、除了从tuple继承的方法以外,nametuple还支持三种方法和一个属性,为了避免和名称冲突,这些方法和属性以下划线开始

#1、nametuple._make(): 从已有的序列或者可迭代对象中创建一个新的对象
from collections import namedtuple

p = namedtuple('Point',['x','y'])
t = [11,22]
p1 = p._make(t)
print(p1)
#执行结果: Point(x=11, y=22)

#2、nametuple._asdict(): 返回一个dict,由名称到对应值建立的映射
p = namedtuple('Point',['x','y'])
t = [33,44]
p1 = p._make(t)
print(p1)   #Point(x=33, y=44)
print(p1._asdict())      #{'x': 33, 'y': 44}
print(type(p1._asdict()))   #<class 'dict'>

#3、nametuple._replace(): 返回一个新的nametuple对象,用新值替换指定名称中的值
p = namedtuple('Point',['x','y'])
t = [55,66]
p1 = p._make(t)
print(p1)        #Point(x=55, y=66)
p2 = p1._replace(x=77)
print(p2)        #Point(x=77, y=66)

#4、nametuple._fields: 以字符串构成元组的形式返回nametuple中的名称,在已存在的nametuple上创建或修改新的nametuple时非常有用
point = namedtuple('Point',['x','y'])
t = [77,88]
p1 = point._make(t)
print(p1)          #Point(x=77, y=88)
color = namedtuple('Color','red green blue')
mix = namedtuple('Mix',point._fields + color._fields)
print(mix(77,88,121,212,0))
#执行结果: Mix(x=77, y=88, red=121, green=212, blue=0)

#通过nametuple._fields创建一个新的nametuple
p = namedtuple('Point',['x','y'])
p1 = namedtuple('Point',p._fields + ('z',))
print(p1._fields)
#执行结果:('x', 'y', 'z')


#枚举类型常量可以通过nametuple来实现
Status = namedtuple('Status','open pending close')
print(Status._make(range(3)))
#执行结果: Status(open=0, pending=1, close=2)
print(Status._fields[0])
#执行结果: open

#另一种实现方式:
"""
class Status0:
     open, pending, close= range(3)
print(Status0.open)
print(Status0.pending)
print(Status0.close)
"""


#nametuple在给csv或者sqlites3返回的元组附上名称特别有用


import csv
EmployeeRecord = namedtuple('EmployRecord','name,age,title,department,paygrade')

for emp in map(EmployeeRecord._make,csv.reader(open("employee.csv",'rb'))):
    print(emp.name,emp.title)

 

上一篇:排序比较器的方法


下一篇:简单游戏物体对象池的实现