命名元组namedtuple
Posted fly-book
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了命名元组namedtuple相关的知识,希望对你有一定的参考价值。
# 命名元组
from collections import namedtuple
subscriber = namedtuple(typename=‘Subscriber‘, field_names=[‘name‘, ‘age‘])
sub = subscriber(‘lisi‘, 10)
print(sub)
print(sub.name)
print(sub.age)
print(len(sub))
name, age = sub
print(name)
print(age)
list1 = [(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]
for rec in list1:
s = subscriber(*rec)
print(s.name, ‘==‘, s.age)
default_sub = subscriber(‘佚名‘, 0)
list2 = [{‘name‘: ‘lisi‘}, {‘name‘: ‘wangwu‘, ‘age‘: 12}, {‘age‘: 11}]
for i in list2:
s = default_sub._replace(**i)
print(s)
# Subscriber(name=‘lisi‘, age=0)
# Subscriber(name=‘wangwu‘, age=12)
# Subscriber(name=‘佚名‘, age=11)
以上是关于命名元组namedtuple的主要内容,如果未能解决你的问题,请参考以下文章