Building unique comma-delimited list?
Duncan Booth
duncan.booth at invalid.invalid
Thu Jan 6 04:27:05 EST 2005
Roy Smith wrote:
> The best I've come up with is the following. Can anybody think of a
> simplier way?
>
> --------------------
> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
>
> # Eliminate the duplicates; probably use set() in Python 2.4
> 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
> --------------------
>
You need to make the dictionary and list types work harder for you. They
have a variety of methods you might find useful.
>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
>>> distinguished = ["foo"]
>>> d = dict.fromkeys(words, True)
>>> newwords = [ w for w in distinguished if d.pop(w, False) ]
>>> newwords.extend(d.keys())
>>> newwords
['foo', 'baz', 'bar']
>>>
More information about the Python-list
mailing list