Counter

Leejaegun·2025년 3월 20일

코딩테스트 시리즈

목록 보기
27/49

🔍 Counter.most_common()이란?

Counter.most_common(n)collections.Counter 객체에서 가장 많이 등장한 요소를 빈도순으로 정렬하여 반환하는 메서드입니다.

📌 기본 문법

from collections import Counter

counts = Counter(iterable)
most_common_elements = counts.most_common(n)

🔹 iterable: Counter 객체를 만들 원본 데이터 (리스트, 문자열 등)
🔹 n (선택 사항): 상위 n개의 요소만 반환 (n을 생략하면 전체 반환)
🔹 반환값: 튜플 리스트 ((요소, 개수))

🔹 예제 1: 리스트에서 가장 많이 등장한 요소 찾기

from collections import Counter

words = ["apple", "banana", "apple", "orange", "banana", "banana", "apple"]
counts = Counter(words)

print(counts.most_common())  # 전체 빈도순 출력
print(counts.most_common(2)) # 상위 2개만 출력

🔹 출력:

[('apple', 3), ('banana', 3), ('orange', 1)]
[('apple', 3), ('banana', 3)]
  • most_common()빈도순 정렬된 리스트 반환
  • most_common(2)빈도 상위 2개만 반환

🔹 예제 2: 문자열에서 가장 많이 등장한 문자 찾기

text = "hello world"
counts = Counter(text)

print(counts.most_common())  # 전체 출력
print(counts.most_common(3)) # 상위 3개 출력

🔹 출력:

[('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
[('l', 3), ('o', 2), ('h', 1)]
  • most_common(3)가장 많이 등장한 문자 3개를 반환

🔹 예제 3: Counter.most_common()을 활용한 문제 해결

📌 가장 많이 등장한 단어 찾기

from collections import Counter
import re

def most_frequent_word(text):
    words = re.findall(r'\w+', text.lower())  # 단어만 추출
    counts = Counter(words)
    return counts.most_common(1)[0][0]  # 가장 많이 등장한 단어 반환

text = "apple banana apple orange banana banana apple"
print(most_frequent_word(text))

🔹 출력:

apple
  • most_common(1)[0][0] → 가장 많이 등장한 단어만 추출

🔹 예제 4: 여러 개의 최빈값 처리

words = ["a", "b", "b", "c", "c", "d"]
counts = Counter(words)

most_common = counts.most_common()
max_count = most_common[0][1]  # 최빈값의 개수
top_elements = [word for word, count in most_common if count == max_count]

print(top_elements)

🔹 출력:

['b', 'c']
  • "b""c"가 가장 많이 등장(2번)했기 때문에 최빈값 리스트 반환

✅ 결론

most_common(n)상위 n개 요소를 빈도순으로 정렬하여 반환
most_common(1)[0][0]가장 많이 등장한 요소만 가져오기
✔ 빈도순 정렬이 필요할 때 빠르게 사용할 수 있음 🚀

profile
Lee_AA

0개의 댓글