转换列表namedtuple

问题描述:

在Python 3,我有一个元组和以下转换列表namedtuple

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 

可以使用参数解包里面做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实现,等等。

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'