Python은 강력한 내장 모듈을 제공하여 코드의 성능을 높일 수 있습니다. 이번 글에서는 몇 가지 기술과 방법을 소개하겠습니다.
1. collections
모듈 활용
Python의 collections
모듈은 딕셔너리, 리스트, 집합과 같은 기본 자료구조를 보강하여 더 나은 성능을 제공합니다. 예를 들어, 대용량 자료구조의 처리에 효율적인 defaultdict
나 Counter
를 사용하는 것이 유용합니다.
from collections import defaultdict, Counter
# defaultdict를 사용한 예시
d = defaultdict(list)
for key, value in some_list_of_pairs:
d[key].append(value)
# Counter를 사용한 예시
word_count = Counter(words_list)
2. itertools
모듈 활용
itertools
모듈은 이터레이터를 만들고 조작하는 데 유용한 함수와 클래스를 제공합니다. 반복문을 사용하지 않고도 빠른 연산이 필요한 경우, 이 모듈을 활용할 수 있습니다.
from itertools import combinations
# combinations를 사용한 예시
comb = combinations(iterable, 3)
3. 내장 함수 활용
Python의 내장 함수를 적절히 활용하여 코드를 간결하게 작성할 수 있습니다. map()
, filter()
, zip()
과 같은 함수를 사용하면 루프를 피하고 처리 속도를 향상시킬 수 있습니다.
# map을 사용한 예시
squared = list(map(lambda x: x**2, some_list))
# filter를 사용한 예시
even_numbers = list(filter(lambda x: x % 2 == 0, some_list))
# zip을 사용한 예시
pairs = list(zip(list1, list2))
내장 모듈을 적재적소에 사용하여 Python 코드의 성능을 향상시킬 수 있습니다. 유의미한 크기의 데이터셋과 연산이 필요한 경우, 위의 방법들을 고려해 보시기를 권장합니다.
참고 문헌:
[1] Python 공식 문서. “collections — Container datatypes”. https://docs.python.org/3/library/collections.html [2] Python 공식 문서. “itertools — Functions creating iterators for efficient looping”. https://docs.python.org/3/library/itertools.html [3] Python 공식 문서. “Built-in Functions”. https://docs.python.org/3/library/functions.html