[TIL](23.07.25.) python Counter

오렌지맛귤·2023년 7월 25일

TIL(Today I Learned !!)

목록 보기
2/5

Python의 Counter기능을 이용해보자!

🍬 리스트 안에 중복된 데이터가 각각 몇개인지 빠르게~ 알 수 있음

from collections import Counter

lst = ['apple', 'mango', 'banana','mango', 'apple', 'banana',
       'mango', 'suhuni']

ret = dict(Counter(lst))
print(ret)      # {'apple': 2, 'mango': 3, 'banana': 2, 'suhuni': 1}

ret = sorted(ret.items(), key = lambda x:x[1], reverse=True)

print(ret)      # [('mango', 3), ('apple', 2), ('banana', 2), ('suhuni', 1)]
print(f'{ret[0][0]}가 {ret[0][1]}번 최다 등장했다!')     # mango가 3번 최다 등장했다!

🍬(문제) 문자열에서 최다 사용된 알파벳 구하기 ㅇㅅㅇ ~

st = 'an applemango'

st_dict = dict(Counter(st))

sorted_st = sorted(st_dict.items(), key= lambda x:x[1], reverse=True)

print(f'{sorted_st[0][0]}가 최다 {sorted_st[0][1]}번 사용됨')

counter 를 이용해 시퀀스에서 중복된 값의 개수를 빠르게 구하는 것과,
내장함수 sorted에서 정렬 기준을 정하는 것을 연습했다!

profile
조수훈입니다.

0개의 댓글