merge & de-duplicate lists

Alan Little contact at alanlittle.org
Wed Oct 8 03:28:09 EDT 2003


I need to merge and de-duplicate some lists, and I have some code
which works but doesn't seem particularly elegant. I was wondering if
somebody could point me at a cleaner way to do it.

Here's my function:

+++++++++++++++++++

from sets import Set

def mergeLists (intialList, sourceOfAdditionalLists,
nameOfMethodToCall) :
    workingSet = Set(initialList)
    for s in sourceOfAdditionalLists :
        getList = s.__getAttribute__(nameOfMethodToCall)
        workingSet = workingSet.union(Set \
            (callable(getList) and getList() or getList))
    return workingSet

++++++++++++++

Two questions - passing the *name* of the method to call, and then
looking it up for each object in the list of extra sources (all of
which need to be new-style objects - not a problem in my application)
seems inelegant. My "sourcesOfAdditionalLists" are normally all of the
same class - is there something I can bind at class level that
automagically refers to instance-level attributes when invoked?

Second (hopefully clearer & less obscure) question : is
sets.Set.union() an efficient way to do list de-duplication? Seems
like the obvious tool for the job.




More information about the Python-list mailing list