Building unique comma-delimited list?

Berthold Höllmann bhoel at despammed.com
Wed Jan 5 23:30:07 CET 2005


roy at panix.com (Roy Smith) writes:

> I've got a silly little problem that I'm solving in C++, but I got to
> thinking about how much easier it would be in Python.  Here's the
> problem:
>
> 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?
...

How about:

.>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
.>>> ', '.join(dict( ( (w,w) for w in words ) ).keys())
'baz, foo, bar'
.>>> words = ["foo",]
.>>> ', '.join(dict( ( (w,w) for w in words ) ).keys())
'foo'

or with Python 2.3 or higher:

.>>> import sets
.>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
.>>> ', '.join(sets.Set(words))
'baz, foo, bar'
.>>> words = ["foo",]
.>>> ', '.join(sets.Set(words))
'foo'


Kind regards
Berthold
-- 
berthold at xn--hllmanns-n4a.de / <http://höllmanns.de/>
bhoel at web.de                 / <http://starship.python.net/crew/bhoel/>



More information about the Python-list mailing list