# Python Lambda 함수 완전 가이드
> 관련 문서: [[02일차_2장 to 2.4_GPT 기초]], [[Python 기초 문법 - 컴프리헨션과 메서드]], [[PyTorch 텐서와 torch.tensor() 완전 가이드]]
## 개요
Lambda 함수는 Python에서 한 줄짜리 간단한 함수를 만드는 방법입니다. 익명 함수라고도 불리며, 간단한 연산을 위해 사용됩니다.
## Lambda 기본 개념
### 정의
**lambda** = "한 줄짜리 간단한 함수를 만드는 방법"
### 기본 문법
```python
lambda 매개변수: 반환값
```
### 가장 간단한 예시
#### def로 만든 함수
```python
def add_one(x):
return x + 1
result = add_one(5)
print(result) # 6
```
#### lambda로 만든 함수
```python
add_one = lambda x: x + 1
result = add_one(5)
print(result) # 6
```
## 토크나이저에서의 Lambda 사용
### 원본 코드
```python
token_encode = lambda s: [character_to_ids[c] for c in s]
token_decode = lambda l: "".join([ids_to_character[i] for i in l])
```
### token_encode 함수 분석
#### lambda 버전
```python
token_encode = lambda s: [character_to_ids[c] for c in s]
```
#### 동일한 def 버전
```python
def token_encode(s):
return [character_to_ids[c] for c in s]
```
#### 더 자세한 def 버전
```python
def token_encode(s):
result = []
for c in s: # 문자열 s의 각 문자 c에 대해
result.append(character_to_ids[c]) # 문자를 숫자로 변환
return result
```
### token_decode 함수 분석
#### lambda 버전
```python
token_decode = lambda l: "".join([ids_to_character[i] for i in l])
```
#### 동일한 def 버전
```python
def token_decode(l):
return "".join([ids_to_character[i] for i in l])
```
#### 더 자세한 def 버전
```python
def token_decode(l):
chars = []
for i in l: # 리스트 l의 각 숫자 i에 대해
chars.append(ids_to_character[i]) # 숫자를 문자로 변환
return "".join(chars) # 문자들을 합쳐서 문자열로
```
## 실제 동작 과정
### token_encode 실행 과정
```python
# 가정: character_to_ids = {'안': 0, '녕': 1, '하': 2}
text = "안녕"
# lambda s: [character_to_ids[c] for c in s]
# s = "안녕"이 들어감
# 리스트 컴프리헨션 실행:
# for c in "안녕": -> c는 '안', 그 다음 '녕'
# [character_to_ids['안'], character_to_ids['녕']]
# [0, 1]
print(token_encode("안녕")) # [0, 1]
```
### token_decode 실행 과정
```python
# 가정: ids_to_character = {0: '안', 1: '녕', 2: '하'}
numbers = [0, 1]
# lambda l: "".join([ids_to_character[i] for i in l])
# l = [0, 1]이 들어감
# 리스트 컴프리헨션 실행:
# for i in [0, 1]: -> i는 0, 그 다음 1
# [ids_to_character[0], ids_to_character[1]]
# ['안', '녕']
# "".join(['안', '녕'])
# "안녕"
print(token_decode([0, 1])) # "안녕"
```
## Lambda vs def 비교
### Lambda가 적합한 경우
#### 1. 아주 간단한 함수
```python
# 제곱 함수
square = lambda x: x * x
print(square(5)) # 25
# 두 수의 합
add = lambda x, y: x + y
print(add(3, 5)) # 8
# 문자열 길이
get_length = lambda s: len(s)
print(get_length("안녕")) # 2
```
#### 2. 한 번만 사용할 함수
```python
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x * x, numbers))
print(squared) # [1, 4, 9, 16]
```
#### 3. 정렬 키로 사용
```python
students = [('철수', 85), ('영희', 92), ('민수', 78)]
sorted_students = sorted(students, key=lambda x: x[1]) # 점수로 정렬
print(sorted_students) # [('민수', 78), ('철수', 85), ('영희', 92)]
```
### def가 적합한 경우
#### 1. 복잡한 로직
```python
def calculate_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
else:
return 'F'
```
#### 2. 여러 줄이 필요한 경우
```python
def process_text(text):
cleaned = text.strip()
upper = cleaned.upper()
words = upper.split()
return len(words)
```
#### 3. 재사용성이 높은 경우
```python
def validate_email(email):
"""이메일 유효성 검사 함수"""
if '@' not in email:
return False
if '.' not in email.split('@')[1]:
return False
return True
```
## 다양한 Lambda 예시
### 기본 연산
```python
# 덧셈
add = lambda x, y: x + y
print(add(3, 5)) # 8
# 곱셈
multiply = lambda x, y: x * y
print(multiply(4, 6)) # 24
# 조건문 포함
is_even = lambda x: x % 2 == 0
print(is_even(4)) # True
print(is_even(3)) # False
# 최댓값
get_max = lambda x, y: x if x > y else y
print(get_max(10, 7)) # 10
```
### 문자열 처리
```python
# 대문자 변환
to_upper = lambda s: s.upper()
print(to_upper("hello")) # "HELLO"
# 문자열 뒤집기
reverse = lambda s: s[::-1]
print(reverse("hello")) # "olleh"
# 첫 글자만
get_first_char = lambda s: s[0] if s else ""
print(get_first_char("Python")) # "P"
```
### 리스트 처리
```python
# 리스트 첫 번째 요소
get_first = lambda lst: lst[0] if lst else None
print(get_first([1, 2, 3])) # 1
# 리스트 길이
get_length = lambda lst: len(lst)
print(get_length([1, 2, 3, 4])) # 4
# 리스트 합계
sum_list = lambda lst: sum(lst)
print(sum_list([1, 2, 3, 4])) # 10
```
## 실제 활용 예시
### map() 함수와 함께
```python
# 리스트의 모든 요소에 함수 적용
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
words = ["hello", "world", "python"]
lengths = list(map(lambda x: len(x), words))
print(lengths) # [5, 5, 6]
```
### filter() 함수와 함께
```python
# 조건에 맞는 요소만 필터링
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
words = ["apple", "banana", "cherry", "date"]
long_words = list(filter(lambda x: len(x) > 5, words))
print(long_words) # ['banana', 'cherry']
```
### sorted() 함수와 함께
```python
# 사용자 정의 정렬
data = [
{'name': '철수', 'age': 25},
{'name': '영희', 'age': 30},
{'name': '민수', 'age': 20}
]
# 나이순 정렬
sorted_by_age = sorted(data, key=lambda x: x['age'])
print(sorted_by_age)
# 이름순 정렬
sorted_by_name = sorted(data, key=lambda x: x['name'])
print(sorted_by_name)
```
## 완전한 토크나이저 예시
```python
# 전체 과정
ko_text = "안녕하세요 반갑습니다"
ko_chars = sorted(list(set(ko_text)))
# 딕셔너리 생성
character_to_ids = {char: i for i, char in enumerate(ko_chars)}
ids_to_character = {i: char for i, char in enumerate(ko_chars)}
# Lambda 함수 정의
token_encode = lambda s: [character_to_ids[c] for c in s]
token_decode = lambda l: "".join([ids_to_character[i] for i in l])
# 테스트
text = "안녕하세요 함께 인공지능을 공부하게 되어 반가워요."
encoded = token_encode(text)
decoded = token_decode(encoded)
print(f"원본 텍스트: {text}")
print(f"인코딩 결과: {encoded}")
print(f"디코딩 결과: {decoded}")
print(f"원본과 일치: {text == decoded}")
```
## 주의사항 및 베스트 프랙티스
### Lambda 사용 시 주의사항
1. **한 줄로 표현 가능한 간단한 로직만** 사용
2. **복잡한 로직은 def 사용** - 가독성이 더 좋음
3. **디버깅이 어려울 수 있음** - 에러 메시지에서 함수명이 `<lambda>`로 표시
4. **문서화가 어려움** - docstring 사용 불가
### 언제 Lambda를 사용할까?
- ✅ **map, filter, sorted의 key 함수로**
- ✅ **간단한 수학 연산**
- ✅ **일회성 함수**
- ❌ **복잡한 비즈니스 로직**
- ❌ **여러 줄이 필요한 경우**
- ❌ **재사용성이 높은 함수**
## 성능 비교
```python
import time
# 성능은 거의 동일
def square_def(x):
return x * x
square_lambda = lambda x: x * x
# 큰 차이 없음
numbers = list(range(1000000))
```
## 요약
- **Lambda** = 한 줄짜리 간단한 함수
- **문법**: `lambda 매개변수: 반환값`
- **용도**: 간단한 연산, map/filter/sorted와 함께 사용
- **장점**: 코드가 간결, 일회성 함수에 적합
- **단점**: 복잡한 로직 표현 어려움, 디버깅 어려움
---
*Tags: #Python #Lambda #익명함수 #함수형프로그래밍 #토크나이저*