从列表创建命名元组

Creating a namedtuple from a list

考虑一个列表变量 t

In [55]: t
Out[55]:
['1.423',
 '0.046',
 '98.521',
 '0.010',
 '0.000',
 '0.000',
 '5814251520.0',
 '769945600.0',
 '18775908352.0',
 '2.45024350208e+11',
 '8131.903',
 '168485.073',
 '0.0',
 '0.0',
 '0.022',
 '372.162',
 '1123.041',
 '1448.424']

现在考虑一个 namedtuple 'Point':

Point = namedtuple('Point', 'usr sys idl wai hiq siq  used  buff  cach  free
    read  writ recv  send majpf minpf alloc  vmfree')

我们如何将变量 t 转换为点?最明显的(无论如何对我来说......)方法 - 仅提供列表作为构造函数参数 - 不起作用:

In [57]: Point(t)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-635019d8b551> in <module>()
----> 1 Point(t)

TypeError: __new__() takes exactly 19 arguments (2 given)

使用 Point(*t) 扩展 t 的内容作为 Point 构造函数的参数。

更有效的解决方案:使用 special _make alternate constructor 直接从任意可迭代构造 namedtuple 而无需创建额外的中间 tuples(作为主构造函数的星形解包要求) .运行速度更快,内存流失更少:

Point._make(t)

尽管名称如此,但 _make public API 的一部分;它以一个前导下划线命名,以避免与字段名称冲突(不允许以下划线开头)。