Building unique comma-delimited list?

Mark McEahern marklists at mceahern.com
Wed Jan 5 17:42:42 EST 2005


Roy Smith wrote:

>You've got a list of words (actually, they're found by searching a
>data structure on the fly, but for now let's assume you've got them as
>a list).  You need to create a comma-delimited list of these words.
>There might be duplicates in the original list, which you want to
>eliminate in the final list.  You don't care what order they're in,
>except that there is a distinguised word which must come first if it
>appears at all.
>
>Some examples ("foo" is the distinguised word): 
>
>["foo"] => "foo"
>["foo", "bar"] => "foo, bar"
>["bar", "foo"] => "foo, bar"
>["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar"
>
>The best I've come up with is the following.  Can anybody think of a
>simplier way?
>  
>
Who knows whether this is "simpler", but it does demonstrate that you 
can customize the sort of a list:

#!/usr/bin/env python

def makesorter(first):
    """Return a sort function that sorts first to the top."""
    def sorter(x, y):
        if x == first:
            return -1
        elif y == first:
            return 1
        else:
            return 0
    return sorter

words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
first = 'foo'
sorter = makesorter(first)
unique = {}
for word in words:
    unique[word] = word
keys = unique.keys()
keys.sort(sorter)
print ', '.join(keys)





More information about the Python-list mailing list