2012-10-14 4 views
2

전 목록을 가져 오는 것이 궁금 해서요. = [1, 5, 2, 5, 1], 고유 값을 필터링하여 반환합니다. 목록에서 한 번만 발생한 숫자입니다. 그러면 결과적으로 나에게 = [2]를 줄 것입니다.필터 목록, 유일한 값 - 파이썬 사용

중복을 필터링하는 방법을 파악할 수 있었지만 이제 중복을 어떻게 제거 할 수 있습니까?

직선 답변 필요 없음, 조금 팁이나 힌트를 환영합니다 :)

내가이 유래에서 찾을 수 있었다. 그것은 내가 원하는 것을 수행하지만 코드를 이해하지 못한다. 누군가 나를 위해 그것을 깰 수 있을까?

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

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

답변

6
>>> a = [1, 5, 2, 5, 1] 
>>> from collections import Counter 
>>> [k for k, c in Counter(a).iteritems() if c == 1] 
[2] 
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]]