[파이썬]Counter 관련 정리

이윤성·2022년 3월 24일
0

Counter는 파이썬의 내부 라이브러리인 collections안에 들어있는 함수로 개수를 셀 때, 유용하다.

기본 쓰임

  • 문자열이나 리스트에서 개수를 셀 때, 사용가능하다.
x = "abc"
# Counter({'a':1, 'b':1, 'c':1})
Counter(x)
  • Counter끼리는 &나 | 연산을 통해 교집합과 합집합을 구할 수 있다.
a = "aabcd"
# Counter({'a':2, 'b':1, 'c':1, 'd':1})
Counter(a)
b = "abbcccd"
# Counter({'a':1, 'b':2, 'c':3, 'd':1})
Counter(b)
# Counter({'a':1, 'b':1, 'c':1, 'd':1})
Counter(a) & Counter(b)
# Counter({'a':2, 'b':2, 'c':3, 'd':1})
Counter(a) | Counter(b)

0개의 댓글

관련 채용 정보