Merging lists has made my brain hurt.

Max M maxm at mxm.dk
Wed Oct 2 17:56:23 EDT 2002


Robert wrote:

> 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 improved:

d = {}
for l in lol:
     for i in l:
         d[i] = d.setdefault(i, 0) + 1
n=len(lol)
common = [e for e in d if d[e]==n]
print common


Or the shortest one I can come up with. Don't know about the brain-pain 
though ;-)

d = {}; common = []
for i in reduce(lambda x,y: x+y, lol):
     d[i] = d.setdefault(i, 0) + 1
     if d[i] == len(lol): common.append(i)
print common


or the perl version:

&_<$>& s_$
print _#($_{})


;-)

-- 


regards Max M

the Law of Inverse Squares. With sound, for example, a source twice as
far away from the detector (an ear?) provides just one-quarter of the
strength of signal. ESP has been said to show no fall-off at all, let
alone any diminution of strength. Well, we must admit that zero signal
won't show any change...




More information about the Python-list mailing list