Search
Duplicate

자주 사용되는 표준 라이브러리

태그
라이브러리
실전에서 유용한 표준 라이브러리
내장함수: 기본 입출력 함수부터 정렬 함수까지 기본적인 함수들을 제공한다.
파이썬 프로그램을 작성할 때 없어서는 안되는 필수적인 기능을 포함하고 있다.
sum(), min(), max(), eval(), sorted()
eval()
result = eval("(3+5)*7") print(result) # output : 56
Python
복사
sorted() with key
array = [('홍길동', 35), ('이순신', 75), ('아무개', 50)] result = sorted(array, key = lambda x : x[1], reverse = True) print(result) # output : # [('이순신', 75), ('아무개', 50), ('홍길동', 35)]
Python
복사
itertools : 파이썬에서 반복되는 형태의 데이터를 처리하기 위한 유용한 기능들을 제공한다.
특히 순열과 조합 라이브러리는 코딩 테스트에서 자주 사용된다.
순열 : 서로 다른 n 개에서 서로 다른 r 개를 선택하여 일렬로 나열하는 것
from itertools import permutations data = ['A', 'B', 'C'] result = list(permutations(data, 3)) print(result) # output : # [('A', 'B', 'C') . . .]
Python
복사
조합 : 서로 다른 n 개에서 순서에 상관 없이 서로 다른 r 개를 선택하는 것
from itertools import combinations data = ['A', 'B', 'C'] result = list(combinations(data, 2)) print(result) # output : # [('A', 'B') . . .]
Python
복사
중복 순열
from itertools import product data = ['A', 'B', 'C'] result = list(product(data, repeat = 2)) print(result)
Python
복사
중복 조합
from itertools import combinations_with_replacement data = ['A', 'B', 'C'] result = list(combinations_with_replacement(data, 2)) print(result)
Python
복사
heapq: 힙(Heap) 자료구조를 제공한다.
일반적으로 우선순위 큐 기능을 구현하기 위해 사용된다.
bisect : 이진 탐색(Binary Search) 기능을 제공합니다.
collections : 덱(deque), 카운터(Counter) 등의 유용한 자료구조를 포함한다.
Counter : 리스트와 같은 반복 가능한 객체가 주어졌을 때 내부의 원소가 몇 번씩 등장했는지를 알려준다.
from collections import Counter counter = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']) print(counter['blue']) # output : 3 print(counter['green']) # output : 1 print(dic(counter) # output : {'red' : 2, 'blue' : 3, 'green' : 1}
Python
복사
math: 필수적인 수학적 기능을 제공한다.
팩토리얼, 제곱근, 최대공약수, 삼각함수 관련 함수부터 파이와 같은 상수를 포함한다.
gcd() : 최대 공약수를 구할 수 있다.
lcm() : 최소 공배수를 구할 수 있다.
import math def lcm(a, b): return a * b // math.gcd(a, b) a = 21 b = 14 print(math.gcd(21, 14)) # output : 7 print(lcm(21, 14)) # output : 42
Python
복사