gpt4 book ai didi

python - 将元组集合压缩到集合中 - python

转载 作者:行者123 更新时间:2023-12-01 04:04:45 26 4
gpt4 key购买 nike

如果我有:

A = {(a,b),(c,d)}
B = {(b,c),(d,e),(x,y)}

当其他元素相同时,我希望使用 A 中的第一个元素和 B 中的第二个元素创建一个新集合:

C = {(a,c),(c,e)}

我已经尝试过:

return {(a,c) for (a,b) in A for (b,c) in B} # nested loop creates too many results

#return {zip(a,c)} in a for (a,b) in A and c for (b,c) in B
#return {(a,c) for (a,c) in zip(A(a,b), B(b,c))}
#return {(a,c) for (a,b) in A for (b,c) in B}

这些不起作用,我不确定我是否完全理解 zip() 函数。

编辑:示例案例错误并添加了一个条件,我需要这样的东西:

return {(a,d) for (a,b) in A for (c,d) in B} # but ONLY when b == c

最佳答案

在你最后一次尝试

{(a,d) for (a,b) in A for (c,d) in B} # but ONLY when b == c

你快明白了。您只需将条件从注释移至集合理解即可:

>>> {(a,d) for (a,b) in A for (c,d) in B if b == c}
{('c', 'e'), ('a', 'c')}

当然,顺序是随机的,因为集合是无序的。

>>> {('c', 'e'), ('a', 'c')} == {('a','c'),('c','e')}
True
>>> {('a','c'),('c','e')}
{('c', 'e'), ('a', 'c')}

关于python - 将元组集合压缩到集合中 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819337/

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