from collections import namedtuple
Person = namedtuple('Person', ('id', 'role', 'name'))
print(Person)
people = [
Person(1, 'Research', 'Ada Lovelace'),
Person(2, 'Scientist', 'Grace Hopper'),
Person._make((3, 'Poet', 'Emily Dickinson')),
Person._make([4, 'Biologist', 'Rachel Carson']),
]
for p in people:
print('R:', p)
print('P:', p.id, p.role, p.name)
i, role, name = p
print('U:', i, role, name)
print('I:', p[0], p[1], p[2])
print('Comparison:', people[0] < people[3], people[0] > people[3])
print('IsInstance:', isinstance(p, tuple))
Point = namedtuple('Point', 'x y')
xs = [Point(x, y) for y in range(2) for x in range(3)]
print(xs)
print(sorted(xs))
Item 32: namedtuple
Posted by Logan Chien