gpt4 book ai didi

python - 动态创建命名元组时的正确格式

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:47 24 4
gpt4 key购买 nike

我创建了一个命名元组并使用它来跟踪单个数据集。当我向namedtuple 添加新的“数据点”时,print() 函数显示我没有相同的确切信息。这是一个例子:

from collections import namedtuple
bbnr = namedtuple('bbnr', ['SN', 'ptr', 'type2'])
DVCS = bbnr('AB01', 101, 'bbnr')
DVCS_b = [DVCS]
print(DVCS_b) # produces [bbnr(SN='AB01', ptr=101, type2='bbnr')]

DVCS = DVCS, bbnr('AB02', 105, 'bbnr')
DVCS_b = [DVCS]
print(DVCS_b) # [(bbnr(SN='AB01', ptr=101, type2='bbnr'), bbnr(SN='AB02', ptr=105, type2='bbnr'))]

请注意,在第二个打印输出中,括号内的整个元组周围有一组额外的括号 ()。

如何在向命名元组添加新元素时保持一致?

最佳答案

您的问题与命名元组无关;你正在创建这些就好了。

相反,您在此处创建了一个元组:

DVCS = DVCS, bbnr('AB02', 105, 'bbnr')

注意逗号;元组由逗号定义,而不是括号:

>>> 1
1
>>> 1,
(1,)
>>> 1, 2
(1, 2)

然后将该元组包装到一个列表对象中。

如果您想要这些值的列表,则只需创建列表:

DVCS_b = [DVCS, bbnr('AB02', 105, 'bbnr')]

或者创建不带 DVCS 值的新命名元组,并采用您从现有列表中创建的先前命名元组:

DVCS = bbnr('AB02', 105, 'bbnr')]
DVCS_b = DVCS_b + [DVCS]

或将其附加到现有列表:

DVCS = bbnr('AB02', 105, 'bbnr')]
DVCS_b.append(DVCS)

关于python - 动态创建命名元组时的正确格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29968509/

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