2013-03-10 50 views
15

在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 

回答

39

可以使用參數解包裏面做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實現,等等。

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'