minimimi
[Python] Collections 모듈: counter, most_common 본문
반응형
counter 함수
collections.Counter(iterable): return dict
예제코드
import collections
a = [1,2,3,4,1,1,2,3,4]
b = [1,2,3,4,1,1,5,6,7]
print(collections.Counter(a),'\n', collections.Counter(b))
print(type(collections.Counter(a)))
결과
>>>
Counter({1: 3, 2: 2, 3: 2, 4: 2})
Counter({1: 3, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1})
<class 'collections.Counter'>
counter 연산
+, -, &(교집합), |(교집합) 연산 가능
예제코드
import collections
a = [1,2,3,4,1,1,2,3,4]
b = [1,2,3,4,1,1,5,6,7]
print(collections.Counter(a))
print(collections.Counter(b))
print(collections.Counter(a) + collections.Counter(b))
print(collections.Counter(a) - collections.Counter(b))
print(collections.Counter(a) & collections.Counter(b))
print(collections.Counter(a) | collections.Counter(b))
결과
>>>
Counter({1: 3, 2: 2, 3: 2, 4: 2})
Counter({1: 3, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1})
Counter({1: 6, 2: 3, 3: 3, 4: 3, 5: 1, 6: 1, 7: 1})
Counter({2: 1, 3: 1, 4: 1})
Counter({1: 3, 2: 1, 3: 1, 4: 1})
Counter({1: 3, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1})
most_common() 함수: 최빈값
collections.Counter(a).most_common(n): return list(tuple)
예제코드
import collections
a = [1,1,1,2,3,2,3,10,9]
print(collections.Counter(a).most_common(3))
결과
>>>
[(1, 3), (2, 2), (3, 2)]
반응형
'프로그래밍 공부 > Python' 카테고리의 다른 글
[Python] 순열, 조합, 중복순열, 중복조합 (0) | 2021.09.30 |
---|