Is there a way to make list comprehension in Python that only contains unique elements?
My initial idea was to use something like this: new_items = [unicode(item) for item in items]
new_items = [unicode(item) for item in items]
However, later I realized that I needed to omit the repeating elements. So, I ended up with this ugly monster:
unique_items = [] for item in items : unicode_item = unicode(item) if unicode_item not in unique_items : unique_items.append(unicode_item)
Now this is much less beautiful (and readable) than a simple list comprehension. So, is there a way to make list comprehension equivalent to the code above?
Order also matters, so I can't just use a set of concepts.
Well, there is no ordered set, but we can abuse OrderedDict:
from collections import OrderedDict t = "never gonna give you up" OrderedDict.fromkeys(t).keys()
gives:
['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']
Your original idea works with a lot of understanding:
new_items = {unicode(item) for item in items}
In short, one slot can be:
s = "some string" unique_items = [unicode(ch) for ch in sorted(set(s), key=s.index)]
Make this an auxiliary function, for example.
def unique_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,
exits
nevrgoa i yup