intersection of 2 list of pairs

John Machin sjmachin at lexicon.net
Sun Feb 20 13:35:58 EST 2005


les_an... at yahoo.com wrote:
> Hi,
> 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.
> So far I have the code below but it does not work out properly, I
would
> be grateful if someone can help me out .
[snip]

This is likely to do what you want, provided the types of the objects
in your tuples define an ordering. The idea is to change the
representation of the tuples to a canonical form (a, b) where a <= b.
By the way, have you considered that there might be duplicates *within*
each list?

>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> s1 = set((min(x,y),max(x,y)) for x, y in E1)
>>> s1
set([('a', 'g'), ('r', 's')])
>>> s2 = set((min(x,y),max(x,y)) for x, y in E2)
>>> s2
set([('a', 'g'), ('q', 'r'), ('f', 'h')])
>>> answer = s1 & s2
>>> answer
set([('a', 'g')])
>>>

Here's a hint: when you find yourself typing stuff like (x[0],x[1])
.... (x[1],x[0]) more than minimally, the 'wrong way, go back' sign
should flash up.

HTH,

John




More information about the Python-list mailing list