简体   繁体   English

Python列表理解,具有唯一项

[英]Python list comprehension, with unique items

Is there a way to make a list comprehension in Python that only contains unique items? 有没有办法在Python中仅包含唯一项的列表理解?

My original idea was to use something like this : new_items = [unicode(item) for item in items] 我最初的想法是使用这样的东西: 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. 顺序也很重要,所以我不能只使用集合理解。

Well, there is no ordered set, but we can misuse OrderedDict: 好吧,没有有序集,但是我们可以滥用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']

您的原始想法具有一定的理解力:

new_items = {unicode(item) for item in items}

I short one liner might be: 我做空一个班轮可能是:

s = "some string"
unique_items = [unicode(ch) for ch in sorted(set(s), key=s.index)]

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 输出

nevrgoaiyup nevrgoaiyup

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM