Building unique comma-delimited list?
Bengt Richter
bokr at oz.net
Thu Jan 6 14:43:30 EST 2005
On 5 Jan 2005 17:05:40 -0500, roy at panix.com (Roy Smith) wrote:
>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?
>
(Not tested beyond what you see ;-)
python 2.4:
>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
>>> w2 = list(t[1] for t in sorted((w!='foo', w) for w in set(words)))
>>> w2
['foo', 'bar', 'baz']
Gets you a sort in the bargain ;-)
>--------------------
>words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
>
># Eliminate the duplicates; probably use set() in Python 2.4
Yup, but 2.3 can be a one-liner too:
>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
>>> w2 = ('foo' in words and ['foo'] or []) + [w for w in dict(zip(words,words)) if w!='foo']
>>> w2
['foo', 'baz', 'bar']
Not sorted, but foo is out front.
>d = dict()
>for w in words:
> d[w] = w
>
>if d.has_key ("foo"):
> newWords = ["foo"]
> del (d["foo"])
>else:
> newWords = []
>
>for w in d.keys():
> newWords.append (w)
>
>s = ', '.join (newWords)
>print s
>--------------------
Regards,
Bengt Richter
More information about the Python-list
mailing list