파이썬 함수 및 데이터 구조 활용 가이드

함수 정의와 호출

파이썬에서 함수는 def 키워드로 선언하며, 타입 힌트를 포함할 수 있다.

def calculate(x: int, y: int, multiplier: int = 1) -> int:
    return (x + y) * multiplier

# 또는 타입 없이도 가능
def calculate(x, y, multiplier=1):
    return (x + y) * multiplier

함수의 타입 정보는 calculate.__annotations__로 확인할 수 있다.

매개변수 전달 방식

# 위치 기반 호출
result = calculate(3, 5)

# 키워드 기반 호출
result = calculate(3, y=5)

가변 인자 처리

  • *args: 임의 개수의 위치 인자를 튜플로 받음
  • **kwargs: 임의 개수의 키워드 인자를 딕셔너리로 받음
def process_data(*values, **options):
    print("Values:", values)      # 튜플 형태
    print("Options:", options)    # 딕셔너리 형태

process_data(1, 2, 3, debug=True, mode='fast')
# Values: (1, 2, 3)
# Options: {'debug': True, 'mode': 'fast'}

시퀀스 언패킹

params = [10, 20, 30]
result = calculate(*params)  # 리스트 요소들을 개별 인자로 전달

config = {'multiplier': 2}
result = calculate(5, 10, **config)  # 딕셔너리 키-값을 키워드 인자로 전달

asterisk(*) 연산자의 다양한 활용

대입문에서의 사용

first, *middle, last = range(6)
# first = 0, middle = [1, 2, 3, 4], last = 5

*initial, final = [10, 20, 30]
# initial = [10, 20], final = 30

시퀀스 언패킹 확장 (Python 3.5+)

# 리스트, 튜플, 집합, 딕셔너리 내부에서 언패킹
numbers = [*range(3)]           # [0, 1, 2]
combined_tuple = (*range(2), 9) # (0, 1, 9)
unique_set = {*range(3), 1, 2}  # {0, 1, 2}
merged_dict = {**{'a': 1}, **{'b': 2}}  # {'a': 1, 'b': 2}

데이터 구조: 리스트, 튜플, 딕셔너리

리스트와 튜플

  • 튜플: 변경 불가능한 순서 있는 컬렉션 ()
  • 리스트: 동적 배열로 크기 조절 가능 []
immutable_data = (10, 20, 30)  # 수정 불가
mutable_list = [1, 2, 3]       # 추가/삭제 가능
mutable_list.append(4)         # [1, 2, 3, 4]

딕셔너리 조작

student = {
    'name': 'Alice',
    'score': 95,
    'grade': 'A'
}

# 값 접근 (키 존재하지 않으면 KeyError 발생)
name = student['name']

# 안전한 접근 방법
score = student.get('score', 0)  # 기본값 설정 가능

# 항목 추가/수정
student['subject'] = 'Math'
student['score'] = 98

# 항목 삭제
del student['grade']

반복문과 컴프리헨션

딕셔너리 순회

data = {'x': 10, 'y': 20, 'z': 30}

# 키만 순회
for key in data:
    print(key)

# 키와 값 모두 순회
for key, value in data.items():
    print(f"{key}: {value}")

범위 기반 반복

# 0부터 9까지
for i in range(10):
    print(i)

# 10부터 19까지
for i in range(10, 20):
    print(i)

리스트 컴프리헨션

# 숫자 리스트 생성
numbers = [i for i in range(1, 11)]              # [1, 2, ..., 10]
doubled = [i * 2 for i in range(1, 6)]           # [2, 4, 6, 8, 10]
strings = [str(i) for i in range(1, 4)]          # ['1', '2', '3']
even_numbers = [i for i in range(1, 11) if i % 2 == 0]  # [2, 4, 6, 8, 10]

예외 처리

try:
    result = 10 / 0
except ZeroDivisionError:
    print("0으로 나눌 수 없습니다")
except ValueError as e:
    print(f"값 오류: {e}")
except Exception:
    print("기타 예외 발생")
else:
    print("예외가 발생하지 않았습니다")  # try 블록 성공 시 실행
finally:
    print("항상 실행되는 코드")         # 예외 여부와 관계없이 실행

유용한 내장 함수 및 기법

문자열 변환

# 진수 변환 포함
number = int("1010", 2)  # 이진수 -> 십진수 (결과: 10)

문자열 포매팅

template1 = "Hello {}, welcome to {}".format("User", "Python")
template2 = "Value: %d, Name: %s" % (42, "Test")

인덱스와 함께 순회

items = ['apple', 'banana', 'cherry']
for index, item in enumerate(items):
    print(f"{index}: {item}")

# 결과: 0: apple, 1: banana, 2: cherry

시간 관련 함수

import time

current_time = time.time()        # Unix timestamp
formatted = time.strftime('%Y-%m-%d %H:%M:%S')
parsed = time.strptime('2023-01-01', '%Y-%m-%d')

태그: python function data-structures dictionary list

5월 20일 12:03에 게시됨