gpt4 book ai didi

python - 将列表转换为命名元组

转载 作者:IT老高 更新时间:2023-10-28 22:24:20 26 4
gpt4 key购买 nike

在 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

最佳答案

你可以做 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 会提供 _make类方法替代构造函数。

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

不要让下划线前缀欺骗你——这个这个类的文档化 API 的一部分,并且可以依赖于所有的 python 实现等等...... p>

关于python - 将列表转换为命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15324547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com