[기본 사용 방식]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from collections import Counter
 
my_list = [1,2,3,4,5,1,1,2,3,3,4]
count = Counter(my_list)   # my_list에 각 개체가 몇 번 나오는지 카운트
 
 
print(count)              
print(count[1])            # 1이 몇번 나왔는지 확인
 
<결과값>
 
<class 'collections.Counter'>
Counter({1333224251})
3

cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from collections import Counter
 
#문자열에 적용
st = "나는 정말하하호호 히히 후후하하하 호호하하"
count = Counter(st)
 
 
print(count)
print(count["하"])
 
<결과값>
 
Counter({'하'7' '4'호'4'히'2'후'2
'나'1'는'1'정'1'말'1})
7

cs


[유용한 메서드]

1
2
3
4
5
6
7
8
9
from collections import Counter
 
count.elements()            
# 개수를 카운트 했던 Counter객체의 dictionary 자료를 다시 반복시켜서 리스트 반환
 
count.most_common(숫자)     #빈도수 순으로 상위 (숫자)개 자료 반환
 
count.subtract(Counter객체) #빼기 
 

cs


+ Recent posts