简体   繁体   中英

zip sets of tuples into set - python

If I have:

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

I'm looking to create a new set with the first element from A and the second element from B when the other elements are the same:

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

I've tried:

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

and

#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}

These just don't work, I'm not sure I fully understand the zip() function.

Edit: had the example case wrong and added a condition, I need something like this:

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

In your last attempt

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

you almost got it. You just need to move the condition from the comment to the set comprehension:

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

Of course, the order is kind of random, since sets are unordered.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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