一、除了从tuple继承的方法以外,nametuple还支持三种方法和一个属性,为了避免和名称冲突,这些方法和属性以下划线开始
#1、nametuple._make(): 从已有的序列或者可迭代对象中创建一个新的对象from collections import namedtuplep = 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创建一个新的nametuplep = 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 csvEmployeeRecord = namedtuple('EmployRecord','name,age,Title,department,paygrade')for emp in map(EmployeeRecord._make,csv.reader(open("employee.csv",'rb'))): print(emp.name,emp.Title)
总结
以上是内存溢出为你收集整理的Python-Collections模块之NameTuple全部内容,希望文章能够帮你解决Python-Collections模块之NameTuple所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)