본문 바로가기

Languages/Python

[파이썬 라이브러리] Collections 모듈의 Counter 클래스

728x90

Counter 소개

from collections import Counter

result_string = Counter('Hello World! hello world')
result_list1 = Counter([1, 2, 2, 3, 3, 3, 4, 4, 4])
#result_list = Counter([1, 2, 2, 3, 3, 3, 4, 4, 4, ['a', 'b']])
result_list2 = Counter([1, 2, 2, 3, 3, 3, 4, 4, 4, ('a', 'b')])
result_tuple = Counter((1, 2, 2, 3, 3, 3, 4, 4, 4, ('a', 'b')))
result_dictionary = Counter({'name': 'pey', 'phone': '0119993323', 'birth': '1118'})
result_set = Counter(set("Hello World!"))

print(result_string)
print(result_list1)
print(result_list2)
print(result_tuple)
print(result_dictionary)
print(result_set)

 

실행 결과

- 5번째 줄 오류 (list 안에 list는 사용 불가)

- string의 경우 글자를 하나씩 카운팅 해줌 (공백도 하나의 문자, 대소문자 구별)

- list 와 tuple 정상 작동 (내부에 tuple이 있을 경우에도 정상 작동)

- dictionary은 그대로 출력 (Counter 객체가 Dictionary 객체와 유사해서?)

- Set은 세어줌 (하지만 당연하게도 1개씩 있음)

 

 

뺄셈 연산

from collections import Counter

result = Counter('Hello World!') - Counter('hello world!')

print(result)

 

실행 결과

- 뺄셈 가능

- 개수가 0개가 되면 사라짐

 

from collections import Counter

result = Counter({'one': 1, 'two': 2, 'three': 3}) - Counter({'one': 1, 'two': 1, 'three': 1})
#result = {'one': 1, 'two': 2, 'three': 3} - Counter({'one': 1, 'two': 1, 'three': 1})

print(result)

 

실행 결과

- Counter 객체 끼리만 뺄셈 가능

- 없는건 그냥 무시 (하단 참조)

 

 

clear 메서드

from collections import Counter

result = Counter('Hello World!').clear()

print(result)

 

- 카운터 객체에서 모든 Key-value 쌍을 제거

 

 

copy 메서드

- 카운터 객체의 복사본을 반환

 

 

elements 메서드

from collections import Counter

result_string = list(Counter('Hello World!').elements())
result_list = list(Counter([1, 2, 3, 4, 2, 3, 4, 3, 4, 4]).elements())

result = list(Counter('Hello World!') - Counter('hello world!'))


print(result_string)
print(result_list)

print(result)

 

실행 결과

- 카운터 객체에서 value만큼 key를 리스트로 변환

- list를 Counter로 변환후 다시 변환하면 순서가 바뀜 (Counter 순서대로)

 

 

get 메서드

from collections import Counter

result = Counter('Hello World!').get('o')

print(result)

 

 

- key를 입력하면 value를 반환

 

 

items 메서드

from collections import Counter

result = Counter('Hello World!').items()

print(result)

 

- key,value 쌍을 튜플의 dict_items 형태로 반환 (Counter도 딕셔너리의 일종인듯)

 

 

keys 메서드

from collections import Counter

result = Counter('Hello World!').keys()

print(result)

 

실행 결과

 

 

most_common 메서드

from collections import Counter

result = Counter('Hello World! hello world!').most_common()

print(result)

 

실행 결과

- most_common 메서드는 가장 많이 나온 순으로 정렬 (튜플 형태)

- 인자로 개수를 전달하면 처음부터 해당 개수까지의 쌍이 반환

 

 

pop 메서드

- 인자로 key를 전달하면 매칭되는 value를 반환하고 카운터 객체에서 해당 쌍 제거

 

 

popitem 메서드

- 인자 없이 가장 마지막 ket,value 쌍을 튜플 형태로 반환하고 제거

 

 

setdefault 메서드

from collections import Counter

result = Counter('!')
result.setdefault('hello')
result.setdefault('world', 1)

print(result)

 

실행 결과

- 새로운 key를 추가

- key만 전달하면 카운트 수는 None

 

 

subtract 메서드

from collections import Counter

result = Counter('abbcccdddd')
result.subtract(['a', 'a', 'b', 'b'])

print(result)

 

실행 결과

- 음수와 0도 표현

 

 

values 메서드

from collections import Counter

result = Counter('abbcccdddd').values()

print(result)

 

실행 결과

- value 들 반환

 

 

기타 연산

from collections import Counter

a = Counter({'a': 1, 'b': 1})
b = Counter({'a': 1, 'b': 3, 'c': 4})

print(a + b)
print(a - b)
print(a & b)
print(a | b)

 

실행 결과

 

반응형