intersection of 2 list of pairs

Peter Otten __peter__ at web.de
Sun Feb 20 12:41:30 EST 2005


les_ander at yahoo.com wrote:

> I have 2 lists of tuples that look like:
> E1=[('a','g'),('r','s')] and
> E2=[('g','a'),('r','q'),('f','h')].
> In this tuple, the ordering does not
> matter, i.e. (u,v) is the same as (v,u).
> 
> What I want to do is the following:
> given 2 list of tuples, E1 and E2, I want to create another list with
> tuples that are common to both. So in the above example I would like
> to return ('a','g') as being common.
> 

How about

>>> e1 = [('a', 'g'), ('r', 's')]
>>> e2 = [('g', 'a'), ('r', 'q'), ('f', 'h')]
>>> s2 = set(e2)
>>> s2.update((b, a) for (a, b) in e2)
>>> list(set(e1) & s2)
[('a', 'g')]

If you are on 2.3, continue to use Set instead of set and modify the update
line to use a list comprehension:

s2.update([(b, a) for (a, b) in e2])

Peter




More information about the Python-list mailing list