Compare tuples of different lenght

John O'Hagan research at johnohagan.com
Sat Aug 20 17:03:05 CEST 2011


On Sat, 20 Aug 2011 01:25:18 -0700 (PDT)
Jurgens de Bruin <debruinjj at gmail.com> wrote:

> Hi,
> 
> I have a list of tuples:
> 
> [(2,),(12,13),(2,3,4),(8,),(5,6),(7,8,9),]
> 
> I would like to compare all the tuples to each other and if one
> element if found two tuples the smallest tuples is removed from the
> list.
[...]

This should work:

def long_match(tuples):
    sorted_tuples = sorted(tuples, key=len)
    for n, t in enumerate(sorted_tuples):
        for s in sorted_tuples[n + 1:]:
            if len(s) > len(t) and any(i in s for i in t):    
                tuples.remove(t)
                break
    return tuples 
 

Regards,

John



More information about the Python-list mailing list