Python 将列表转换为namedtuple

Python 将列表转换为namedtuple,python,Python,在python 3中,我有一个元组行和一个列表a: Row = namedtuple('Row', ['first', 'second', 'third']) A = ['1', '2', '3'] 如何使用列表A初始化行?请注意,在我的情况下,我不能直接这样做: newRow = Row('1', '2', '3') 我尝试过不同的方法 1. newRow = Row(Row(x) for x in A) 2. newRow = Row() + data # don

在python 3中,我有一个元组
和一个列表
a

Row = namedtuple('Row', ['first', 'second', 'third'])
A = ['1', '2', '3']
如何使用列表
A
初始化
?请注意,在我的情况下,我不能直接这样做:

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
您可以使用参数解包来执行
行(*A)

>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row(*A)
Row(first='1', second='2', third='3')
请注意,如果您的linter没有太多抱怨使用以下划线开头的方法,
namedtuple
提供了一个classmethod替代构造函数

>>> Row._make([1, 2, 3])

不要让下划线前缀蒙蔽了你——这是这个类的有文档记录的API的一部分,可以在所有python实现中使用,等等。

namedtuple子类有一个名为“\u make”的方法。 将数组(Python列表)插入到命名的tuple对象中使用方法“\u 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'