繁体   English   中英

将元组压缩成集合-python

[英]zip sets of tuples into set - python

如果我有:

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')}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM