[EMAIL PROTECTED] (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 -- [EMAIL PROTECTED] / <http://höllmanns.de/> [EMAIL PROTECTED] / <http://starship.python.net/crew/bhoel/> -- http://mail.python.org/mailman/listinfo/python-list