efficient list merging

Mark McEahern marklists at mceahern.com
Wed Sep 4 10:48:34 EDT 2002

Question:  What if lol1 had ['g', 'f']?  Would that be considered the same
as ['f', 'g']?

Anyway, here's yet another approach:

#! /usr/bin/env python

lol1 = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j']]
lol2 = [['d', 'e', 'f'], ['k', 'l', 'm'], ['d'], ['f', 'g'], ['a']]

def mergelists(*lists):
    d = {}
    for each_list in lists:
        for item in each_list:
            key = str(item)
            if key not in d:
                d[key] = item
    ret = d.values()
    return ret

mergelol = mergelists(lol1, lol2)

expected = [['a'], ['a', 'b', 'c'], ['d'], ['d', 'e', 'f'], ['f', 'g'],
            ['g', 'h', 'i', 'j'], ['k', 'l', 'm']]

assert mergelol == expected

// m


More information about the Python-list mailing list