collections 모듈의 Counter 클래스

C__W.A·2021년 7월 28일
0

Python

목록 보기
3/6
post-thumbnail

✅Counter 클래스

데이터의 개수를 알고 싶을 때가 있다. 그럴 때 사용하는 파이썬의 collections 모듈의 Counter클래스이다.

from collections import Counter

data = [2, 2, 2, 1, 1, 3, 3, 4]

make_dict = Counter(data)

print(make_dict)
->
Counter({2: 3, 1: 2, 3: 2, 4: 1})

Counter 클래스는 배열을 딕셔너리 형태로 만들어 준다. key값은 리스트에 값을 value는 데이터의 개수를 나타낸다. 예를 들어 [1, 1, 6, 6, 6, 8, 9]라는 리스트가 있다고 하자. 이 리스트를 Counter클래스를 이용해서 딕셔너리를 만들면 {1:2, 6:3, 8:1, 9:1}형태로 반환해준다.

문자열도 똑같이 동작한다.

from collections import Counter

s = "hello python"

make_dict = Counter(s)

print(make_dict)
->
Counter({'h': 2, 'l': 2, 'o': 2, 'e': 1, ' ': 1, 'p': 1, 'y': 1, 't': 1, 'n': 1})

✅배열로 정리하고 싶을 때

Counter 클래스로 정리한 데이터를 정렬된 배열로 리턴하고 싶은 때가 있다. 그럴 때 사용하는 메서드는 most_common이다. most_common을 사용하면 갯수가 많은 순으로 정렬된다. 반환값으로 중복된 값과 갯수가 함께 나온다.

from collections import Counter

s = "hello world"

make_dict = Counter(s).most_common()

print(make_dict)

->
[('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]

✅ 교집합과 합집합 구현

Counter 메서드는 set() 함수와 마찬가지로 집합 구조를 생성할 수 있다.
교집합은 & , 합집합은 | 표현으로 set함수와 똑같이 작동한다.
뉴스 클러스터링(프로그래머스 카카오) 문제 풀이 일부

s1 = Counter("FRANCE")
s2 = Counter("french")

first = list((s1 & s2).elements())
second = list((s1 | s2).elements())

print(first, second)

실행결과 :
 ['f', 'r', 'n', 'c', 'e'] ['f', 'r', 'a', 'n', 'c', 'e', 'h']

0개의 댓글