728x90
이 글은 슬기로운 파이썬 트릭의 내용을 정리한 글입니다.
3.2 람다는 단일 표현식 함수다
- lambda 키워드는 익명 함수를 선언하는 방법이다.
- 익명 함수라는 말은 함수를
def function_name(parameters):
와 같은 방식으로 선언한 경우 함수 객체를function_name
에 바인딩해 사용하는데 그럴 필요가 없다는 말이다. - 아래의
add
함수와add_lambda
는 같은 역할을 한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def addx,yx,y: | |
return x + y | |
add_lambda = lambda x, y: x+y |
- 람다 함수를 사용하게 되면 코드 def로 함수를 선언하는 몇 줄을 줄일 수 있지만 과도하게 사용하면 코드의 유지보수 측면에서 악영향을 줄 수 있다.
- 사용의 간결함과 유지보수의 악영향을 주지 않는 적정선에서 사용하는 것이 좋다.
람다 함수를 사용하기 좋은 경우
- list를 sorting할 때 key를 정의할 때 사용하기에 편리하다.
- 다음과 같이 tuple을 element로 가지는 list를 sorting할 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Students = [3,′C′3,′C′, 2,′B′2,′B′, 1,′A′1,′A′] | |
sorted_students = sortedStudents,key=lambdax:x[0]Students,key=lambdax:x[0] | |
>>> [1,′A′1,′A′, 2,′B′2,′B′, 3,′C′3,′C′] |
마무리
- 아주 간단한 함수를 정의할 때는 사용할 수 있지만 조금만 단계가 복잡해지면 사용할 수 없을 것 같고, 누구나 다 알 수 있는 내용이 아니라면 설명을 추가해줘야할 것 같다.
- 위에서 사용한 list를 sorting하는 경우 외에는 유용함을 찾지 못했다.
'프로그래밍 언어 > python' 카테고리의 다른 글
*args와 **kwargs 활용하기 00 | 2022.07.26 |
---|---|
matplotlib 테마 설정하기 00 | 2022.07.26 |
유연한 matplotlib subplot 사용하기 00 | 2022.07.26 |
numpy array를 사용할 때 for문을 피해야하는 이유 00 | 2022.07.26 |
python 함수를 아름답게 사용하기 00 | 2022.07.26 |