Python列表理解,具有唯一项 [英] Python list comprehension, with unique items

查看:91
本文介绍了Python列表理解,具有唯一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在仅包含唯一项的Python中进行列表理解?

Is there a way to make a list comprehension in Python that only contains unique items?

我最初的想法是使用这样的东西: new_items = [unicode(item) for item in 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.

推荐答案

好,没有有序集,但是我们可以误用OrderedDict:

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()

赠予:

['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p']

这篇关于Python列表理解,具有唯一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆