过滤列表,只有唯一值 - 使用python

时间:2012-10-14 03:06:37

标签: python filter

我想知道如何获取列表,ex a = [1,5,2,5,1],并让它过滤掉唯一值,这样它只返回一个只在列表中出现一次的数字。所以它会给我一个= [2]的结果。

我能够弄清楚如何过滤重复项,现在我将如何摆脱重复项?

不需要直接回答,只需要一点提示或提示:)

我能够在stackoverflow上找到它。它做我想要的,但我不明白代码,有人可以为我分解吗?

d = {}
for i in l: d[i] = d.has_key(i)

[k for k in d.keys() if not d[k]]

2 个答案:

答案 0 :(得分:6)

>>> a = [1, 5, 2, 5, 1]
>>> from collections import Counter
>>> [k for k, c in Counter(a).iteritems() if c == 1]
[2]

答案 1 :(得分:0)

听到您的代码所做的事情:

d = {}
for i in list:
    # if the item is already in the dictionary then map it to True,
    # otherwise map it to False 
    # the first time a given item is seen it will be assigned False,
    # the next time True
    d[i] = d.has_key(i)

# pull out all the keys in the dictionary that are equal to False
# these are items in the original list that were only seen once in the loop
[k for k in d.keys() if not d[k]]