티스토리 뷰

데이터 개수 셀 때 사용할 수 있는 counter 에 대해서 알아보자.

counter는 collections 모듈로부터 import하여 사용한다.

 

[1] 사용 방법

먼저, counter 라이브러리를 사용하기 위해서는 맨 위에 다음 문장을 추가한다.

from collections import Counter

 

[2] 사용 예시

만약, 한 문장 안에 단어별로 개수를 센다고 가정해보자.

sentence = "helloworld"
sentence_dict = {}
for s in sentence:
    if s in sentence_dict.keys():
        sentence_dict[s] += 1
    else:
        sentence_dict[s] = 1
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}

"helloworld"라는 문장 안의 단어들의 개수를 세는 코드이다.

이처럼 python의 dictionary를 사용하여 각 단어들의 개수를 셀 수 있다.

하지만, counter를 사용하면 한 줄로 표현이 가능하다.

 

sentence = "helloworld"
Counter(sentence)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})

 

또한, 개수가 가장 많은 순으로도 출력할 수 있다.

Counter(sentence).most_common()
# [('l', 3), ('o', 2), ('h', 1), ('e', 1), ('w', 1), ('r', 1), ('d', 1)]

 

[카카오 2021 매뉴리뉴얼]

카카오 2021 매뉴리뉴얼 문제를 풀 때 기존 방식대로 dictionary를 사용하였는데,

정답 코드를 참고한 뒤, counter를 사용해보았다.

from itertools import combinations
from collections import Counter

def solution(orders, course):
    answer = []
    for k in course:
        candidates = []
        for order in orders:
            # 1. 각 메뉴별로 조합을 구한다(단, 메뉴는 2개 이상으로)
            for _li in combinations(order, k):
                res = ''.join(sorted(_li))
                candidates.append(res)
                
        # 2. 카운터 정렬
        sorted_candidates = Counter(candidates).most_common()
        print(sorted_candidates)
        
        # 카운트가 2 이상이면서 가장 첫번째 키운터 원소와 같은 것만 answer에 넣는다.
        for menu, cnt in sorted_candidates:
            if cnt>1 and cnt == sorted_candidates[0][1]:
                answer.append(menu)
    return sorted(answer)

solution(["XYZ", "XWY", "WXA"], [2,3,4])
# [('XY', 2), ('WX', 2), ('XZ', 1), ('YZ', 1), ('WY', 1), ('AW', 1), ('AX', 1)]
#[('XYZ', 1), ('WXY', 1), ('AWX', 1)]

조합으로 구한 list를 기준으로 개수를 구해주고 있다.

most_common() 를 사용하여 정렬도 진행되었다.한 줄로 개수구하기 + 정렬을 한번에 할 수 있다는 장점이 있다.

 

[3] 마무리

클린 코드를 짜기 위한 방법 중 하나는 코드를 간결하게 하는 것이다.

파이썬에서 제공되는 라이브러리도 숙지해서 조금 더 간결하게 코드를 작성해보자!!!

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함