将列表转换为命名元组

41
在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个回答

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实现中都存在等等...

有点俗套 - 但我刚学到了你10年前就知道的东西。非常感谢过去的你以及现在的你为帮助他人走过难关! - CocoaEv

1

命名元组子类有一个名为 '_make' 的方法。使用 '_make' 方法将数组(Python列表)插入到命名元组对象中非常容易:

>>> 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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接