python 中有一个非常接近数学表达的元组 namedtuple,它继承自 tuple,是具有命名字段的元组子类。本篇介绍它的使用方法。所有代码在 jupyterlab 中演示。

官方示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from collections import namedtuple

namedtuple?

Signature:
namedtuple(
typename,
field_names,
*,
rename=False,
defaults=None,
module=None,
)
Docstring:
Returns a new subclass of tuple with named fields.

>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
File: /usr/local/miniconda/lib/python3.9/collections/__init__.py
Type: function

个人示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from collections import namedtuple

User = namedtuple('User', ['name', 'sex', 'age'])

user = User(name='lisi', sex='female', age=21)
user
# User(name='lisi', sex='female', age=21)

user = User._make(['xulai', 'male', 24])
user
# User(name='xulai', sex='male', age=24)

user.name, user.sex, user.age
# ('xulai', 'male', 22)

user = user._replace(age=22)
user
# User(name='xulai', sex='male', age=22)

d = user._asdict()
d
# {'name': 'xulai', 'sex': 'male', 'age': 22}

namedtuple('User', d.keys())(**d)
User(name='xulai', sex='male', age=22)

参考文献

  1. Python的namedtuple使用详解