1. 콜백 함수(Callback Function)
다른 함수의 인자로 전달되어 실행되는 함수이다. 일반적으로 어떤 작업이 완료된 후 특정 동작을 수행하기 위해 사용된다.
def callback_func(func):
for i in range(5):
func()
def print_hello()
print('안녕하세요 파이썬'
print_hello()
callback_func(print_hello)
def callback_func(func, num):
for i in range(num):
func(i)
def print_hello(num):
print('안녕하세요 파이썬', num)
def print_hi(num):
print('하이 파이썬', num)
callback_func(print_hello, 3)
callback_func(print_hi, 4)
2. 람다 함수(Lambda Finction)
짧고 간단한 함수를 한 줄로 생성할 때 사용하는 구문이다.
lambda arguments: expression
def square(x):
return x**2
print(square(5))
square = lambda x: x**2
print(square(5))
(lambda x: x**2)(5)
people = [
{'name':'오렌지', 'age':30},
{'name':'김사과', 'age':20},
{'name':'반하나', 'age':25}
]
def sort_age(x):
return x['age']
people[0]
print(sort_age(people[0]))
sorted_people = sorted(people, key=sort_age)
print(sorted_people)
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)
3. 람다가 유용하게 사용되는 대표적인 함수
3-1. filter 함수
파이썬의 내장 함수이다. 주로 리스트나 순차적인 데이터 타입에서 함수의 조건을 만족하는 항목들만 남기고 싶을 때 사용한다.
li = [2, 5, 7, 10, 15, 17, 20, 22, 25, 28]
def even(n):
if n%2 == 0:
return True
else:
return False
result = list(filter(even, li))
print(result)
result = list(filter(lambda n: n%2 == 0, li))
print(result)
3-2. map 함수
파이썬의 내장 함수이다. 주로 리스트나 순차적인 데이터 타입에서 모든 항목에 함수의 조건을 적용하고 싶을 때 사용한다.
num = [1, 2, 3, 4, 5]
squared_num = list(map(lambda x: x**2, num))
print(squared_num)
li1 = [1, 2, 3]
li2 = [4, 5, 6]
sum = list(map(lambda x, y: x+y, li1, li2))
print(sum)
words = ['apple', 'banana', 'orange', 'cherry']
upper_words = list(map(lambda x: x.upper(), words))
print(upper_words)
'파이썬 > 파이썬 기초 문법' 카테고리의 다른 글
클로저와 데코레이터 (1) | 2024.10.14 |
---|---|
객체지향과 클래스 (0) | 2024.10.14 |
파이썬 변수의 범위 (2) | 2024.09.30 |
파이썬 사용자 정의 함수와 None (0) | 2024.09.30 |
파이썬의 컬렉션과 반복문 (1) | 2024.09.26 |