What is the best way to merge two lists?

Wojtek Walczak gminick at hacker.pl
Sun Nov 17 11:21:52 EST 2002


Dnia Sun, 17 Nov 2002 10:38:16 -0500, Pierre Rouleau napisał(a):
[...] 
> Is there a more efficient way to merge heterogenous lists than the brute 
> force approach used by uniq() above?
Functions:

--- flatten() ---
import types

flatret = []

def flatten(x, a=1):
   for i in x:
     if type(i) == types.ListType or type(i) == types.TupleType:
        flatten(i, 0)
     else:
        flatret.append(i)
   if a==1:
      return flatret
---------------

--- mergelist() ---
def mergelist(*lists):
   c = {}
   [[c.__setitem__(a,0) for a in flatten(i)] for i in lists]
   return c.keys()
-------------------

A code to check if it works:

---
def nic():
   pass

a = [1,2,3,[3]]
b = [4,'b',1]
c = [5,nic,['a', nic, 'b', [1, nic, 'b']]]
d = [2,'a',8]
e = [7,6,3]
f = [1,nic,3]

print mergelist(a,b,c,d,e)
---

...and it returns that: 
      ['a', 1, 2, 3, 4, 5, 6, 7, 8, <function nic at 0x814880c>, 'b']

HTH in any way... ;>

-- 
[ ] gminick (at) underground.org.pl  http://gminick.linuxsecurity.pl/ [ ]
[ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ]



More information about the Python-list mailing list