Python list comprehension, with unique items

2019-06-17 02:57发布

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 items]

However, I later realized that I needed to omit duplicate items. So I ended up with this ugly monstrosity :

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 far less pretty (and readable) than a simple list comprehension. So, is there a way to make a list comprehension equivalent to the above code?

Also order does matter, so I can't just use a set comprehension.

4条回答
Fickle 薄情
2楼-- · 2019-06-17 03:21

Make it a helper function, like so.

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,

outputs

n e v r g o a i y u p

查看更多
男人必须洒脱
3楼-- · 2019-06-17 03:37

Your original idea works with a set comprehension:

new_items = {unicode(item) for item in items}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-06-17 03:42

I short one liner might be:

s = "some string"
unique_items = [unicode(ch) for ch in sorted(set(s), key=s.index)]
查看更多
再贱就再见
5楼-- · 2019-06-17 03:44

Well, there is no ordered set, but we can misuse 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']
查看更多
登录 后发表回答