将列表转换为namedtup

2024-09-28 05:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Row = namedtuple('Row', ['first', 'second', 'third'])
A = ['1', '2', '3']

如何使用列表初始化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

Tags: 方法in列表fordata情况namedtuplerow
2条回答

可以使用参数解包来完成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')

请注意,如果linter没有太多抱怨使用以下划线开头的方法,namedtuple提供了一个^{}类方法替代构造函数。

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

不要让下划线前缀愚弄您——这个是这个类的API文档的部分,可以依赖于它在所有python实现中的存在,等等。。。

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

相关问题 更多 >

    热门问题