코테 유용한 기능 Python Counter

유알·2024년 5월 22일
0

코테에서 특정 컬렉션 안에 특정 원소가 몇개 들어있는지 세는 경우는 매우 많이 나온다.
나의 경우 딕셔너리를 만들고 하나하나 추가하는 코드를 작성했었는데, 오늘 좀 신박한 기능을 알았다.

설명보다는 코드로 보여주겠다.

원소의 갯수가 몇개인지 세준다

약간 딕셔너리랑 동작이 비슷하다

args = [
    [1,2,3,1,2],
    [1,1,1,1,1],
    [1,1,1,2,2],
]

from collections import Counter

for arg in args:
    print("=====================")
    print("arg :", arg)
    c = Counter(arg)
    print("c :", c)
    print("c.most_common(1) :", c.most_common(1))
    print("c[1] :", c[1])

출력

=====================
arg : [1, 2, 3, 1, 2]
c : Counter({1: 2, 2: 2, 3: 1})
c.most_common(1) : [(1, 2)]
c[1] : 2
=====================
arg : [1, 1, 1, 1, 1]
c : Counter({1: 5})
c.most_common(1) : [(1, 5)]
c[1] : 5
=====================
arg : [1, 1, 1, 2, 2]
c : Counter({1: 3, 2: 2})
c.most_common(1) : [(1, 3)]
c[1] : 3

각 원소가 몇개인지 딕셔너리를 만들어 주었고, most_common을 사용해서 top n의 튜블을 반환해준다. ㄷㄷ

빼기 더하기도 가능하다

args = [
    [1,2,3,1,2],
    [1,1,1,1,1],
    [1,1,1,2,2],
]

from collections import Counter

total = Counter()
print(total)
for arg in args:
    c = Counter(arg)
    print(" + ", c)
    total += c

print(total)

출력

Counter()
 +  Counter({1: 2, 2: 2, 3: 1})
 +  Counter({1: 5})
 +  Counter({1: 3, 2: 2})
Counter({1: 10, 2: 4, 3: 1})
args = [
    [1,2,3,1,2],
    [1,1,1,1,1],
    [1,1,1,2,2],
]

from collections import Counter

total = Counter([1] * 9 + [2] * 9 + [3] * 9)

print(total)
for arg in args:
    c = Counter(arg)
    print(" - ", c)
    total -= c

print(total)

출력

Counter({1: 9, 2: 9, 3: 9})
 -  Counter({1: 2, 2: 2, 3: 1})
 -  Counter({1: 5})
 -  Counter({1: 3, 2: 2})
Counter({3: 8, 2: 5})

후기..

뭐 구현은 어렵지 않긴 한데, 너무 편리하다..
특히 저 빼기 더하기는 완전 유용할듯

profile
더 좋은 구조를 고민하는 개발자 입니다

0개의 댓글