Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python的namedtuple命名元组

$
0
0

python有一个类似tuple的容器namedtuples(命名元组),位于collection模块中。namedtuple是继承自tuple的子类,可创建一个和tuple类似的对象,而且对象拥有可访问的属性。

示例1:

import collections # 创建namedtuple Student = collections.namedtuple('Student',['name','age','id']) # 初始化 S = Student('snail','23','14335') # 使用下标访问 print(S[1])# 23 # 使用名字访问 print(S.name)# snail # 使用getattr()访问 print(getattr(S,'id'))# 14335

示例2:

import collections # 创建namedtuple Student = collections.namedtuple('Student',['name','age','id']) # 初始化 S = Student('snail','23','14335') # 获得字段名 print(S._fields)# ('name', 'age', 'id') # 更改值 print(S._replace(name = 'test'))# Student(name='test', age='23', id='14335') # namedtuple转为OrderedDict print(S._asdict())# OrderedDict([('name', 'snail'), ('age', '23'), ('id', '14335')]) # 使用list构造namedtuple li = ['panda', '12', '32343' ] print(Student._make(li))# Student(name='panda', age='12', id='32343') # 使用dict构造namedtuple di = { 'name' : "sucker", 'age' : 34 , 'id' : '544554' } print(Student(**di))# Student(name='sucker', age=34, id='544554') namedtuple文档: https://docs.python.org/3/library/collections.html#collections.namedtuple

Viewing all articles
Browse latest Browse all 9596

Trending Articles