- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambdaEx.py
More file actions
Latest commit
44 lines (35 loc) · 1.61 KB
/
Copy pathlambdaEx.py
File metadata and controls
44 lines (35 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 람다 : 이름 없는 한 줄 함수
# lambda 매개변수: 반환식
# test/lambda1.py 에서 맛만 봤던 것을 제대로 다룹니다
add=lambdaa, b: a+b
print(add(3, 4))
# 위는 아래와 완전히 같다
defadd2(a, b):
returna+b
print(add2(3, 4))
print('---------- 람다는 이렇게 쓰라고 만든 게 아닙니다 ----------')
# 변수에 담을 거면 그냥 def 를 쓰세요. 이름이 있어야 에러 메시지도 친절합니다.
# 람다는 "함수를 인자로 넘길 때" 빛납니다.
print('---------- sorted 의 key ----------')
students= [
{'이름': '홍길동', '점수': 85},
{'이름': '김길동', '점수': 92},
{'이름': '최길동', '점수': 78},
]
by_score=sorted(students, key=lambdas: s['점수'], reverse=True)
forsinby_score:
print(s['이름'], s['점수'])
words= ['banana', 'kiwi', 'apple']
print('길이순 :', sorted(words, key=lambdaw: len(w)))
print('사전순 :', sorted(words))
print('---------- map : 모든 원소를 변환 ----------')
nums= [1, 2, 3, 4]
print(list(map(lambdan: n*10, nums)))
print([n*10forninnums]) # 컴프리헨션이 더 읽기 쉽다
print('---------- filter : 조건에 맞는 것만 ----------')
print(list(filter(lambdan: n%2==0, nums)))
print([nforninnumsifn%2==0]) # 이것도 컴프리헨션이 낫다
print('---------- 정리 ----------')
# map / filter 는 컴프리헨션으로 대체 가능하고 대개 그쪽이 읽기 좋습니다.
# 람다가 정말 필요한 곳은 sorted / max / min 의 key 입니다.
print('최고점 :', max(students, key=lambdas: s['점수'])['이름'])