过滤器列表,只有唯一值 - 与python
问题描述:
我想知道我将如何采取一个列表,例如= [1,5,2,5,1],并让它过滤出唯一值,以便它只返回一个只在列表中出现一次的数字。所以它会给我一个结果= [2]。过滤器列表,只有唯一值 - 与python
我能弄清楚如何过滤掉重复,现在我该如何摆脱重复?
无需直答案,只是有一些小技巧或暗示都是欢迎的。
我能找到这个计算器上。它做我想要的,但我不明白的代码,但有人可以为我分解?
d = {}
for i in l: d[i] = d.has_key(i)
[k for k in d.keys() if not d[k]]
答
>>> a = [1, 5, 2, 5, 1]
>>> from collections import Counter
>>> [k for k, c in Counter(a).iteritems() if c == 1]
[2]
答
听到的是你的代码做什么:
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]]