Merging lists has made my brain hurt.

Robert k.robert at gmx.de
Wed Oct 2 15:28:03 EDT 2002


> 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']

using 'reduce' would be nice functional style programming. however calls &
copying, creating, slicing, modifying lists are very expensive while running
is so-la-la. so a simple breaky 2D-loop would almost outperform at minimum
cons-ing and still read best for newbies:

common=[]
for e in lol[0]:
    for l in lol:
        if e not in l: break
    else: common.append(e)

#(the else belongs to for!)
#in certain cases when NX&NY are both huge, a dict would gain O(2) speed but
only if you play economically with one dict! :

common=[]
d={}
for l in lol:
    for e in l:
        if e in d:    d[e]+=1
        else:        d[e]=1
n=len(lol)
common = [e for e in d if d[e]==n]
print common

#(slightly improveable); but if you have your input sub-lists occasionally
prepared as dicts (sets in the future), the first solution is again
prefereable for small & huge stuff without code modification

Robert





More information about the Python-list mailing list