gpt4 book ai didi

python set union 操作在命名元组中表现不佳

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:57 25 4
gpt4 key购买 nike

我想在 python 中创建一组 namedtuple,能够使用联合操作动态添加元素。

下面的代码片段创建了 namedtupleset,表现良好。

from collections import namedtuple

B = namedtuple('B', 'name x')

b1 = B('b1',90)
b2 = B('b2',92)
s = set([b1,b2])
print(s)

打印

{B(name='b1', x=90), B(name='b2', x=92)}

现在,如果我创建另一个 namedtuple 并使用 union 操作将其添加到我的 set 中,它不会按预期运行。

b3 = B('b3',93)
s = s.union(b3)
print(s)

代码片段打印以下输出。

{93, B(name='b1', x=90), B(name='b2', x=92), 'b3'}

预期的输出应该是:

{B(name='b1', x=90), B(name='b2', x=92), B(name='b3', x=93)}

我是否误解了 API?python2 和 3 都表现出相同的行为。

最佳答案

namedtuple 实例是一个可迭代的项目。 set.union 只是将当前集合与 namedtuple 中的项目合并。

但是,您想要的是将 namedtuple 放入另一个容器/iterable 中,因此合并是使用新父 iterable 中包含的项目(namedtuple)完成的:

s.union((b3,))

如果你真的认为运算符等价,它会变得更加明显:

s = s | set(b3) # set(b3) -> {93, 'b3'}

与我们实际想要的相比:

s = s | {b3}

union 与外部可迭代对象一起执行。

关于python set union 操作在命名元组中表现不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962469/

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