Programming/Python

[Python] Counter: list 요소 개수 세어서 dictionary로 출력

당닝 2021. 7. 11. 22:08
728x90

리스트의 모든 요소의 개수를 세서 dictionary로 출력하기를 원한다면 Counter을 사용하면 된다.

collections 모듈 내에 존재하므로 import collections를 해주어야한다.

 

import collections

list1 = [1, 2, 10, 1, 4, 10, 2, 1, 1, 10]
print(collections.Counter(list1))
''' >> Counter({1: 4, 10: 3, 2: 2, 4: 1})'''

list2 = [1, 2, 10, 1, 4, 10, 2, 1, 1]
print(collections.Counter(list2))
''' >> Counter({1: 4, 2: 2, 10: 2, 4: 1})'''

 

- 두 Counter 비교하기

print(collections.Counter(list1) - collections.Counter(list2))
''' >> Counter({10: 1})'''

print(collections.Counter(list1) + collections.Counter(list2))
''' >> Counter({1: 8, 10: 5, 2: 4, 4: 2})'''

print(collections.Counter(list1) & collections.Counter(list2))
''' >> Counter({1: 4, 2: 2, 10: 2, 4: 1})'''

print(collections.Counter(list1) | collections.Counter(list2))
''' >> Counter({1: 4, 10: 3, 2: 2, 4: 1})'''

 

- 형태 변환하기

print(list(collections.Counter(list1)))
''' >> [1, 2, 10, 4]'''

print(dict(collections.Counter(list1)))
''' >> {1: 4, 2: 2, 10: 3, 4: 1}'''

print(set(collections.Counter(list1)))
''' >> {1, 2, 10, 4}'''

print(collections.Counter(list1).most_common())
''' >> [(1, 4), (10, 3), (2, 2), (4, 1)]'''

 

728x90