본문 바로가기

Python/공부공부

[Python] collections.Counter

 

collections.Counter

리스트나 문자열 같은 반복 가능한(iterable) 객체에서 각 요소가 몇 번 등장했는지 빈도수 반환.

from collections import Counter

s = "banana"
counter = Counter(s)

print(counter)         # Counter({'a': 3, 'n': 2, 'b': 1})
print(counter['a'])    # 3
print(counter['z'])    # 0 (없는 값은 0)

 


 

* most_common()

빈도수 내림차순으로 (원소, 개수) 튜플을 리스트로 반환.

# 빈도수대로 나열
print(counter.most_common())	# [('a', 3), ('n', 2), ('b', 1)]

# 상위 n개 나열
print(counter.most_common(2))	# [('a', 3), ('n', 2)]

 


 

* 카운터 간 연산

from collections import Counter

c1 = Counter("banana")   # Counter({'a': 3, 'n': 2, 'b': 1})
c2 = Counter("band")     # Counter({'b': 1, 'a': 1, 'n': 1, 'd': 1})

print(c1 + c2)   # Counter({'a': 4, 'n': 3, 'b': 2, 'd': 1})
print(c1 - c2)   # Counter({'a': 2, 'n': 1})
print(c1 & c2)   # Counter({'a': 1, 'n': 1, 'b': 1})
print(c1 | c2)   # Counter({'a': 3, 'n': 2, 'b': 1, 'd': 1})
  • + : 합 -> 빈도수의 합
  • - : 차 -> 빈도수 차 (음수는 0으로 처리)
  • & : 교집합 -> 공통된 원소 중 최소값
  • | : 합집합 -> 각 요소별 최대값

 


 

* subtract()

뺄셈 메서드, ( - ) 연산자와  달리 음수 결과 유지.

from collections import Counter

c1 = Counter("banana")   # Counter({'a': 3, 'n': 2, 'b': 1})
c2 = Counter("band")     # Counter({'b': 1, 'a': 1, 'n': 1, 'd': 1})

# 빼기 수행
c1.subtract(c2)
print(c1)		# Counter({'a': 2, 'n': 1, 'b': 0, 'd': -1})

 

리스트로 빼기 : 리스트에 있는 요소들 각각 -1 처리

c = Counter("banana")   # Counter({'a': 3, 'n': 2, 'b': 1})

c.subtract(["a", "n", "x"])
print(c)		# Counter({'a': 2, 'n': 1, 'b': 1, 'x': -1})

 

딕셔너리로 빼기 : dict의 value값만큼 삘셈 처리

c = Counter("banana")   # Counter({'a': 3, 'n': 2, 'b': 1})

c.subtract({"a": 2, "b": 1, "z": 3})
print(c)		# Counter({'n': 2, 'a': 1, 'b': 0, 'z': -3})

 


* subtract()

덧셈 메서드, ( + ) 연산자와 달리 새로운 Counter 반환

from collections import Counter

c1 = Counter("banana")   # Counter({'a': 3, 'n': 2, 'b': 1})
c2 = Counter("band")     # Counter({'b': 1, 'a': 1, 'n': 1, 'd': 1})

c1.update(c2)
print(c1)		# Counter({'a': 4, 'n': 3, 'b': 2, 'd': 1})
  • c1 + c2 -> 원본 변경 X, 새로운 Counter 반환.
  • c1.update(c2) -> c1자체가 변경.

 

iterable 업데이트

** 문자열도 iterable → 문자열인 경우, 각 글자 카운트 추가

c = Counter("banana")    # Counter({'a': 3, 'n': 2, 'b': 1})

c.update("band")         
print(c)		# Counter({'a': 4, 'n': 3, 'b': 2, 'd': 1})

 

딕셔너리 업데이트 : dict의 value값만큼 덧셈 처리

c = Counter("banana")    # Counter({'a': 3, 'n': 2, 'b': 1})

c.update({"a": 5, "x": 2})   
print(c)		# Counter({'a': 8, 'n': 2, 'b': 1, 'x': 2})

 


 

* total()     --> Python 3.10 부터 가능

from collections import Counter

c1 = Counter("banana")   # Counter({'a': 3, 'n': 2, 'b': 1})
c2 = Counter("band")     # Counter({'b': 1, 'a': 1, 'n': 1, 'd': 1})

c = c1 + c2
print(c.total()) 	# 10