프로그래머스-메뉴 리뉴얼

Minji·2022년 4월 25일
0

코딩테스트 연습

목록 보기
3/11

python

Counter 클래스

collections 모듈의 Counter 함수
컨테이너 안의 데이터를 편리하고 빠르게 개수를 세도록 지원하는 계수기 도구

from collections import Counter

list=['A','B','C','A','A','B','B','B']
print(Counter(list))
#Counter({'B':4,'A':3,'C':1})

요소의 갯수를 구해주며, 요소의 개수가 많은 것 부터 출력해준다.

print(Counter('AAABBC'))
#Counter({'A': 3, 'B': 2, 'C': 1})

Counter 클래스의 함수

elements()

단순히 요소를 각각 출력해주는 역할, 대소문자 구분함

from collections import Counter

tmp = Counter("I love you")
print(list(tmp.elements()))
# ['I', ' ', ' ', 'l', 'o', 'o', 'v', 'e', 'y', 'u']

most_common(n)

최빈값을 n개 반환한다. 결과값의 자료형은 Tuple

from collections import Counter

list=['A','B','C','A','A','B','B','B']
print(Counter(list).most_common())
print(Counter(list).most_common(2))

#[('B',4),('A',3),('C',1)]
#[('B',4),('A',3)]

subtract()

요소를 빼주는 역할, 요소가 없을 때는 음수의 값이 반환됨

from collections import Counter

ex_counter1 = Counter('My name is M')
ex_counter2 = Counter('Your name is M')
# 2번 카운터 - 1번 카운터
ex_counter2.subtract(ex_counter1)
print(ex_counter2)
# Counter({'Y': 1, 'o': 1, 'u': 1, 'r': 1, ' ': 0, 'n': 0, 'a': 0, 'm': 0, 'e': 0, 'i': 0, 's': 0, 'M': -1, 'y': -1})

combintaions 모듈

from itertools import combinations
items=['A','B','C']
list(combincatinos(itmes,2))
#[('A','B'),('A','C'),('B','C')]

combinations(list,n) 형식으로 사용함
n개의 조합으로 이뤄진 리스트를 반환함

여러키로 정렬하기

sorted, lambda식 이용하여 여러키로 정렬 가능

list=[{'point':100,'name':'B'},{'point':80,'name':'A'},{'point':80,'name':'C'}]
sorted_list= sorted(list,key= lambda k:(k['point'],k['name']))
#{'point':80,'name':'A'},{'point':80,'name':'C'},{'point':100,'name':'B'}
sorted_list= sorted(list,key= lambda k:(-k['point'],k['name']))
#{'point':100,'name':'B'},{'point':80,'name':'A'},{'point':80,'name':'C'}
  • point순으로 정렬 후, 같은 point면 name순으로 정렬
  • -(마이너스)붙으면 역순으로 정렬
profile
매일매일 성장하기 : )

0개의 댓글