-->

[파이썬] collections 모듈, 리스트 요소별 개수 쉽게 구하기

리스트 ["a","b","a","c","d","e","c","c"]가 있다고 해보자. 각 요소별 갯수를 구해야 할 때, 아래와 같이 딕셔너리에는 키 값이 하나만 존재한다는 특징을 사용해 구할 수 있을 것이다.

 

dict={}
test=["a","b","a","c","d","e","c","c"]

for v in test:
	if dict.get(v): dict[v]+=1
	else: dict[v]=1

print(dict)
{'a': 3, 'b': 2, 'c': 4, 'd': 2, 'e': 2}

 

 

위와 같은 방식으로도 구할 수는 있지만 collections 모듈의 Count를 사용하면 손쉽게 구할 수 있다.

 

import collections

dict={}
test=["a","b","a","c","d","e","c","c"]

dict=collections.Counter(test)
print(dict)
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1, 'e': 1})

 

 

또한 Counter로 얻은 딕셔너리끼리는 뺄셈도 가능하다.

 

import collections

test1=["a","b","a","c","d","e","c","c"]
test2=["a","b","a","c","d","e","c"]

dic1=collections.Counter(test1)
dic2=collections.Counter(test2)

print(dic1-dic2)
Counter({'c': 1})

 

댓글

Designed by JB FACTORY