标准的元组:
p1 = ('Baby', 18, 'male')
print('Person1:', p1)
p2 = ('Jay', 16, 'female')
print('The name of Person2:', p2[0])
print('\nPerson:')
for p in [p1, p2]:
print('%s is a %d year old %s' % p)
#结果
Person1: ('Baby', 18, 'male')
The name of Person2: Jay
Person:
Baby is a 18 year old male
Jay is a 16 year old female
?通过nametuple()创建类,参数包括类名称和包含元素名称的字符串
from collections import namedtuple
#创建一个nametuplede 类,类名称为Person,并赋给变量P
P = namedtuple('Person', 'name,age,gender')
print('Type of Person:', type(P))
p1 = P(name='Baby', age=18, gender='male')
print('\nRepresentation:', p1)
p2 = P(name='Jay', age=16, gender='female')
print('The name of Person2:', p2.name)
print('\nFields by index:')
for p in [p1, p2]:
print('%s is a %d year old %s' % p)
## 结果
Type of Person: <class 'type'>
Representation: Person(name='Baby', age=18, gender='male')
The name of Person2: Jay
Fields by index:
Baby is a 18 year old male
Jay is a 16 year old female
非法的参数值:
# 参数字段的名称非法,包含系统名称class
try:
P1 = namedtuple('Person','age,name,class,gender')
print(P1._fields)
except ValueError as err:
print(err)
print()
# 类成员字段参数名称重复 age
try:
P2 = namedtuple('Person','age,gender,name,age')
print(P2._fields)
except ValueError as err:
print(err)
## 结果
Type names and field names cannot be a keyword: 'class'
Encountered duplicate field name: 'age'
将参数rename设置为True,系统自动将错误的参数替换为?"下划线+参数索引" 。
try:
P1 = namedtuple('Person','age,name,class,gender',rename=True)
print(P1._fields)
except ValueError as err:
print(err)
print()
try:
P2 = namedtuple('Person','age,gender,name,age',rename=True)
print(P2._fields)
except ValueError as err:
print(err)
## 结果
('age', 'name', '_2', 'gender')
('age', 'gender', 'name', '_3')
|