Python - 11. 내장 함수와 표준 라이브러리
2025. 1. 19. 23:18ㆍ프로그래밍 언어/Python
Python은 다양한 내장 함수와 표준 라이브러리를 제공하여 프로그래밍을 더욱 효율적이고 생산적으로 만들어줍니다. 이번 섹션에서는 주요 내장 함수와 자주 사용되는 표준 라이브러리 모듈들을 살펴봅니다.
11.1 주요 내장 함수
Python에는 자주 사용되는 함수들이 내장되어 있습니다. 아래는 그 중 일부입니다:
데이터형 변환 함수
- int(), float(), str(), bool()
- 예제:
print(int("123")) # 123
print(float("3.14")) # 3.14
print(str(123)) # '123'
print(bool(0)) # False
수학 함수
- abs(): 절대값 반환
- round(): 반올림
- pow(): 거듭제곱 계산
print(abs(-5)) # 5
print(round(3.14159, 2)) # 3.14
print(pow(2, 3)) # 8
반복과 필터링
- map(), filter(), zip()
- 예제:
nums = [1, 2, 3]
squares = map(lambda x: x ** 2, nums)
print(list(squares)) # [1, 4, 9]
even = filter(lambda x: x % 2 == 0, nums)
print(list(even)) # [2]
letters = ["a", "b", "c"]
print(list(zip(nums, letters))) # [(1, 'a'), (2, 'b'), (3, 'c')]
정렬과 검색
- sorted(), max(), min()
- 예제:
nums = [3, 1, 4, 1, 5, 9]
print(sorted(nums)) # [1, 1, 3, 4, 5, 9]
print(max(nums)) # 9
print(min(nums)) # 1
기타 유용한 함수
- enumerate(): 인덱스와 값을 함께 반환
- any(): 하나라도 참이면 True 반환
- all(): 모두 참이면 True 반환
items = [0, 1, 2]
for index, value in enumerate(items):
print(index, value) # 0 0, 1 1, 2 2
print(any([0, 0, 1])) # True
print(all([0, 1, 2])) # False
개발 도구 함수
- dir(): 객체의 속성과 메서드 확인
- help(): 객체에 대한 문서화 문자열 표시
print(dir(str)) # 문자열 관련 메서드 확인
help(str.upper) # str.upper 메서드의 도움말 출력
11.2 itertools 모듈
itertools는 반복 가능한 데이터 처리를 위한 도구들을 제공합니다.
주요 함수
- count(): 무한 카운터 생성
- cycle(): 반복 가능한 데이터 무한 순환
- permutations(), combinations(): 순열과 조합 생성
import itertools
# count 예제
for i in itertools.count(10):
print(i)
if i > 12:
break
# combinations 예제
items = ["a", "b", "c"]
print(list(itertools.combinations(items, 2))) # [('a', 'b'), ('a', 'c'), ('b', 'c')]
11.3 functools 모듈
functools는 함수형 프로그래밍 도구를 제공합니다.
주요 함수
- reduce(): 누적 계산 수행
- partial(): 함수 일부 인수를 고정
- lru_cache(): 함수 호출 결과를 캐싱
from functools import reduce, partial, lru_cache
# reduce 예제
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # 24
# partial 예제
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
print(square(4)) # 16
# lru_cache 예제
@lru_cache(maxsize=32)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # 55
11.4 operator 모듈
operator는 함수 형태로 제공되는 연산자를 포함합니다.
주요 함수
- add(), mul(), itemgetter(), attrgetter()
import operator
print(operator.add(10, 20)) # 30
print(operator.mul(10, 5)) # 50
# itemgetter 예제
data = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
print(sorted(data, key=operator.itemgetter(1))) # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
11.5 collections.abc 모듈
collections.abc는 컨테이너 타입의 추상 베이스 클래스(ABC)를 정의합니다.
주요 ABC
- Iterable, Sequence, Mapping
from collections.abc import Iterable, Sequence
nums = [1, 2, 3]
print(isinstance(nums, Iterable)) # True
print(isinstance(nums, Sequence)) # True
11.6 contextlib 모듈
contextlib는 컨텍스트 관리자 생성과 관련된 도구를 제공합니다.
주요 함수
- contextmanager
from contextlib import contextmanager
@contextmanager
def open_file(file, mode):
f = open(file, mode)
try:
yield f
finally:
f.close()
with open_file("example.txt", "w") as file:
file.write("Hello, World!")
11.7 math, datetime, random 모듈
math
수학 관련 함수 제공
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
datetime
날짜와 시간 처리
from datetime import datetime
now = datetime.now()
print(now) # 현재 날짜와 시간 출력
random
난수 생성
import random
print(random.randint(1, 10)) # 1에서 10 사이의 정수
print(random.choice(["red", "blue", "green"])) # 리스트에서 임의의 요소 선택
11.8 os, sys, json 모듈
os 모듈
운영 체제와 상호작용하기 위한 도구를 제공합니다.
import os
print(os.getcwd()) # 현재 작업 디렉터리
os.makedirs("new_folder", exist_ok=True) # 디렉터리 생성
os.remove("example.txt") # 파일 삭제
sys 모듈
Python 인터프리터와 상호작용하는 도구를 제공합니다.
import sys
print(sys.version) # Python 버전 출력
print(sys.platform) # 현재 플랫폼 출력
sys.exit(0) # 프로그램 종료
json 모듈
JSON 데이터를 처리합니다.
import json
data = {"name": "Alice", "age": 25}
# JSON 직렬화
json_string = json.dumps(data)
print(json_string) # '{"name": "Alice", "age": 25}'
# JSON 역직렬화
parsed_data = json.loads(json_string)
print(parsed_data) # {'name': 'Alice', 'age': 25}
이번 섹션에서는 Python의 내장 함수와 표준 라이브러리를 활용하는 방법을 다뤘습니다.
'프로그래밍 언어 > Python' 카테고리의 다른 글
Python - 12. 동시성과 병렬 처리 (0) | 2025.01.20 |
---|---|
Python Tkinter - 1. 소개와 기본 위젯 (0) | 2025.01.20 |
Python - 10. 모듈과 패키지 (0) | 2025.01.19 |
Python - 9. 객체 지향 프로그래밍 (0) | 2025.01.19 |
Python - 8. 예외 처리 (0) | 2025.01.19 |