Today I Learned | 6월 23일 collections모듈의 Counter 클래스

juri·2021년 6월 23일
0

TIL

목록 보기
4/25
post-thumbnail

📢 Counter

단어를 이루는 알파벳의 갯수를 dict 형식으로 반환함.

from collections import Counter

print(Counter('hello'))
#Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
print(Counter('hello').items())
#dict_items([('h', 1), ('e', 1), ('l', 2), ('o', 1)])

👉김왼손의 왼손코딩 1일1파이썬 15

2개 이상있는 알파벳을 골라내는 함수 만들기

def filter_unique(word) :
    return [item for item, count in Counter(word).items() 
            if count > 1]
    
filter_unique('apple')
#['p']

위와 반대로 오직 1개만 있는 알파벳을 골라내는 함수는?

alist = []
def filter_non_unique(word) :
    counter = Counter(word)
    for word in counter :
        if counter[word] == 1:
            alist.append(word)
    return alist

filter_non_unique('hello')
#['h', 'e', 'o']
  • .items()를 쓰지 않아도 Counterkey, value값을 나눠서 사용할 수 있다.
  • [x for x]를 쓰지 않고 풀어쓰면 코드가 좀 길어지긴 하지만 이해하기 더 쉽다.
  • for word in counter 에서 볼 수 있듯이 word에는 counter의 key값이 나온다. -> value값을 counter[word]의 형식으로 나타낼 수 있음

iterable 형식 비교

🍟 Counter

print(Counter('hello')
#Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

value값을 기준으로 내림차순 배열된다.

🍟 items.() (리스트안의 튜플)

print(Counter('hello').items())
#dict_items([('h', 1), ('e', 1), ('l', 2), ('o', 1)])

🍟 dictionary

print(dict(Counter('hello')))
#{'h': 1, 'e': 1, 'l': 2, 'o': 1}

🍟 list

print(list(Counter('hello')))
#['h', 'e', 'l', 'o']

key값만 남는다.


단어 속 갯수가 가장 많은 알파벳 찾아내기

version01

from collections import Counter


def max_find(word):
    finder = Counter(word).items()
    max_number = 0
    for key, value in finder :
        if value > max_number :
            max_number = value
            max_alpha = key
    return max_alpha, max_number

print(max_find('helllllllo'))
#('l', 7)

version02

from collections import Counter

def max_find(word):
    finder = Counter(word)
    max_number = 0
    for x in finder :
        if finder[x] > max_number :
            max_number = finder[x]
            max_alpha = x
    return max_alpha, max_number
    
print(max_find('hello july'))
#('l', 3)
profile
Make my day !

0개의 댓글