[210124 TIL] Algorithm Tips(Counter, sorted, fstring)
Today I Learned
written by 602
collections.Counter()
-
빈도 순으로 정렬할 때 자주 쓰이는 collections 모듈의 Counter 함수
-
return: dict
-
input: list, dict, str 등
-
methods(메소드)
-
update()
: 입력값이 str과 같이 문자열 형태일 때 결과값이 dict 형태가 될 수 있도록 해줌import collections # 리스트 part = ["mislav", "stanko", "mislav", "ana"] counter = collections.Counter(part) print(counter) ''' 결과 Counter({'mislav': 2, 'stanko': 1, 'ana': 1}) ''' # 문자열 counter = collections.Counter() counter.update("Juliaaa") print(counter) ''' 결과 Counter({'a': 3, 'J': 1, 'u': 1, 'l': 1, 'i': 1}) '''
-
elements()
: 입력값의 요소 반환 (입력순서대로 or 알파벳 순 정렬)# 문자열 counter = collections.Counter("Juliaaa") print(list(counter.elements())) print(sorted(counter.elements())) ''' 결과 ['J', 'u', 'l', 'i', 'a', 'a', 'a'] #무작위 반환(입력 순서대로) ['J', 'a', 'a', 'a', 'i', 'l', 'u'] #알파벳 순 정렬 ''' # 리스트 part = ["mislav", "stanko", "mislav", "ana"] counter = collections.Counter(part) print(list(counter.elements())) print(sorted(counter.elements())) ''' 결과 ['mislav', 'mislav', 'stanko', 'ana'] ['ana', 'mislav', 'mislav', 'stanko'] '''
-
most_common(n)
: 입력값에서 최다 빈도 등장 n개 리스트로 반환g = ["classic", "pop", "classic", "classic", "pop", "dance", "dance", "dance", "dance"] counter = collections.Counter(g) print(counter.most_common()) # 빈도 순으로 전부 출력 print(counter.most_common(2)) # 최다 빈도 2개 출력 ''' 결과 [('dance', 4), ('classic', 3), ('pop', 2)] [('dance', 4), ('classic', 3)] '''
-
Sorted, Key, Lambda
- 파이썬 정렬함수 중 하나인
sorted()
key
,lambda
와 함께 쓰면 정렬 기준을 지정할 수 있다.
# original
nums = [7,3,37,73,33,77]
print(sorted(nums)) #오름차순
print(sorted(nums, reverse=True)) #내림차순
'''
결과
[3, 7, 33, 37, 73, 77]
[77, 73, 37, 33, 7, 3]
'''
# key: 정렬의 기준
## list
names = ["Jane", "Mike", "Julia", "Christoper", "Min"]
print(sorted(names, key=len))
print(sorted(names, key=lambda x: x[0])) #첫번째 알파벳 기준
'''
결과
['Min', 'Jane', 'Mike', 'Julia', 'Christoper']
['Christoper', 'Jane', 'Julia', 'Mike', 'Min']
'''
## dict
students = {"Jane":5, "Mike":2, "Julia":10, "Min":2}
print(sorted(students)) #알파벳 순서
print(sorted(students, key=lambda x: (students[x], len(x)))) #value값 -> key 문자열 길이 (오름차순)
print(sorted(students, key=lambda x: (students[x], len(x)), reverse=True)) #역순(내림차순)
'''
결과
['Jane', 'Julia', 'Mike', 'Min']
['Min', 'Mike', 'Jane', 'Julia']
['Julia', 'Jane', 'Mike', 'Min']
'''
Pythonic Code
파이썬스러운 깔끔하고 효율적인 코드 작성하기
(파이썬에서는 코드를 최대한 간략히 줄여쓰는 것이 pythonic하다고 불리우는거 같다. 그렇다고 너무 과하게 줄이는건 가독성 측면에서 오히려 마이너스이기에 적당히 알아볼 수 있는 선에서 줄여나가는게 좋다고 생각한다.)
-
list, dict 내부 for문
# 빈(0으로 채워진) list/array 생성 new_list = [0 for _ in range(5)] # 1차원 리스트(1,5) new_array = [[0 for _ in range(3)] for _ in range(5)] # 2차원 배열(5,3) print(new_list) print(new_array) ''' 결과 [0, 0, 0, 0, 0] [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] ''' # 빈 list를 value로 하는 초기 딕셔너리 생성 ## defaultdict와 비슷 g = ["classic", "pop", "classic", "classic", "pop", "dance"] new_dict = {x:[] for x in set(g)} print(new_dict) ## if(조건문) 추가 new_dict = {x:[] for x in set(g) if "p" in x} print(new_dict) ''' 결과 {'pop': [], 'classic': [], 'dance': []} {'pop': []} '''
-
fstring
{}.format()
을 대체할 요즘 대세fstring
# 기본 a, b = "훌리아", "줄리아" print(f"{a}는 {b}보다 낫다.") ''' 결과 훌리아는 줄리아보다 낫다. ''' # 추가 기능 prop = "37" print(f'{prop:10}') #공백, 왼쪽 끝으로 print(f'{prop:>10}') #공백, 오른쪽 끝으로 print(f'{prop:*<10}') #*, 왼쪽 끝으로 print(f'{prop:*>10}') #*, 오른쪽 끝으로 print(f'{prop:*^10}') #*, 가운데 정렬 pi = 3.141592 print(f'{pi:.2f}') #소수점 아래 둘째 자리까지 ''' 결과 37 37 37******** ********37 ****37**** 3.14 '''
Author And Source
이 문제에 관하여([210124 TIL] Algorithm Tips(Counter, sorted, fstring)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@yookyungkho/210124-TIL-Today-I-Learned저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)