2

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

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

不需要直接的答案,欢迎提供一点提示或提示:)

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

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

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

2 回答 2

6
>>> a = [1, 5, 2, 5, 1]
>>> from collections import Counter
>>> [k for k, c in Counter(a).iteritems() if c == 1]
[2]
于 2012-10-14T03:09:07.790 回答
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]]
于 2012-10-14T04:55:34.993 回答