merge & de-duplicate lists
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Wed Oct 8 06:18:29 EDT 2003
Alan Little wrote:
> 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?
If they all are of the same class, you may just introduce method to call
that returns your lists.
BTW, your design might be not perfect. I personally whould rather split
this function into a couple: one to merge lists and the second that will
produce lists to merege (this approach might help with the problem above).
regards,
anton.
More information about the Python-list
mailing list