将元组集压缩到集合中 - 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')}
如果我有:
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')}