Merging lists has made my brain hurt.

gyromagnetic gyromagnetic at excite.com
Fri Oct 4 09:05:04 EDT 2002


Huw Lynes <huw at moving-picture.com> wrote in message news:<3D9B1953.3030109 at moving-picture.com>...
> Hi All,
> 
> I have a list containing an arbitrary number of other lists. The 
> internal lists contain strings. For example
> lol = [
> ['aaa', 'bbb', 'ccc'],
> ['bbb', 'ccc', 'ddd'],
> ['ccc', 'ddd', 'eee']
> ]
> 
> I want to merge the three lists into a single list that only contains 
> the strings present in all three lists. In the above case I want to end 
> up with
> ['ccc']
> 
> This has me utterly stumped. Any help is appreciated.The only articles 
> about merging strings that I've managed to find so far have been about 
> merging strings so that you don't get repeats. Not quite what I'm 
> looking for.
> 
> Thanks,
> Huw


Hi Huw,
I caught this thread rather late, but here's another variation on the
theme. Not sure how it compares with the other approaches in terms of
speed, efficiency, etc.

-gyro

=====

#!/usr/bin/python

def common_entries(lol):

    mst = dict(zip(lol[0],[1]*len(lol[0])))

    for kk in mst.keys():
        for ll in lol[1:]:
            if kk in ll: mst[kk] += 1

    return [ss for ss,i in mst.items() if i == len(lol)]



More information about the Python-list mailing list