Python List Comprehension, With Unique Items
Is there a way to make a list comprehension in Python that only contains unique items? My original idea was to use something like this : new_items = [unicode(item) for item in item
Solution 1:
Well, there is no ordered set, but we can misuse OrderedDict:
from collections importOrderedDictt="never gonna give you up"
OrderedDict.fromkeys(t).keys()
Gives:
['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']
Solution 2:
Solution 3:
I short one liner might be:
s = "some string"unique_items = [unicode(ch) for ch in sorted(set(s), key=s.index)]
Solution 4:
Make it a helper function, like so.
defunique_iter(iterable):
seen = set()
for item in iterable:
if item in seen:
continue
seen.add(item)
yield item
for ch in unique_iter("never gonna give you up"):
print ch,
outputs
n e v r g o a i y u p
Post a Comment for "Python List Comprehension, With Unique Items"