将列表转换为命名元组
在Python 3中,我有一个元组 Row
和一个列表 A
:
Row = namedtuple('Row', ['first', 'second', 'third'])
A = ['1', '2', '3']
我该如何用列表 A
来初始化 Row
呢?请注意,在我的情况下,我不能直接这样做:
newRow = Row('1', '2', '3')
我尝试了不同的方法
1. newRow = Row(Row(x) for x in A)
2. newRow = Row() + data # don't know if it is correct
2 个回答
1
这个叫做namedtuple的子类里面有一个方法叫做'_make'。如果你想把一个数组(也就是Python中的列表)放进namedtuple对象里,使用'_make'这个方法就很简单了:
>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row._make(A)
Row(first='1', second='2', third='3')
>>> c = Row._make(A)
>>> c.first
'1'
83
你可以使用 Row(*A)
这个方式,它是通过参数解包来实现的。
>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row(*A)
Row(first='1', second='2', third='3')
需要注意的是,如果你的代码检查工具对以单下划线开头的方法没有太多抱怨,namedtuple
提供了一个 _make
的类方法作为替代构造函数。
>>> Row._make([1, 2, 3])
别被这个下划线前缀给迷惑了——这 确实 是这个类的文档化 API 的一部分,可以在所有的 Python 实现中依赖它的存在,等等……