Python

2020. 08. 25 python

씬프 2020. 8. 25. 08:48
반응형

Filter_unique

 

리스트에서 유일한 value를 잡아내는 함수.

 

리스트에서 값들의 갯수를 찾아내기 위해

collections 모듈의 Counter 클래스를 사용한다.

 

from collections import Counter

def filter_unique(lst):
	return [item for item, count in Counter(lst).items() if count > 1]

Counter(lst)는 딕셔너리를 출력한다.

key = 리스트의 value, value = count 값

Counter(lst)를 통해 출력된 딕셔너리의 key와 value를

각각 item과 count로 넘기고

count > 1인 경우만 출력한다면 unique하지 않은 값을 출력할 수 있다.

 

from collections import Counter

def filter_unique(lst):
	return [item for item, count in Counter(lst).items() if count == 1]

위와 같이 if count == 1로 수정한다면,

오직 하나만 있는 unique한 값을 필터링할 수 있다.

 

출처 : https://www.30secondsofcode.org/python/s/filter-unique

'Python' 카테고리의 다른 글

Django User 모델 정리  (0) 2021.03.17
2020. 08. 26 python  (0) 2020.08.26
2020. 08. 24 python  (0) 2020.08.24