Skip to content

Repository files navigation

description Python의 λžŒλ‹€(lambda)ν•¨μˆ˜λŠ” 이름 없이 μ •μ˜λ˜λŠ” 읡λͺ… ν•¨μˆ˜λ‘œ, 주둜 κ°„λ‹¨ν•œ μ—°μ‚°μ΄λ‚˜ μΌνšŒμ„± μ²˜λ¦¬κ°€ ν•„μš”ν•œ κ²½μš°μ— μ‚¬μš©λœλ‹€. def ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ ν•¨μˆ˜λ₯Ό μ •μ˜ ν•˜λŠ” 것과 달리, λžŒλ‹€ ν•¨μˆ˜λŠ” ν•œ μ€„λ‘œ κ°„κ²°ν•˜κ²Œ ν‘œν˜„ν•  수 μžˆλ‹€.

lambda

lambda λ§€κ°œλ³€μˆ˜λ“€: ν‘œν˜„μ‹
  • λ§€κ°œλ³€μˆ˜λ“€ : ν•¨μˆ˜μ— 전달될 μΈμžλ“€μ„ μ§€μ •ν•œλ‹€.
  • ν‘œν˜„μ‹ : λ§€κ°œλ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ 계산될 식을 μž‘μ„±ν•˜λ©° 이 값이 λ°˜ν™˜λœλ‹€.

예λ₯Ό λ“€μ–΄, 두 수의 합을 κ΅¬ν•˜λŠ” λžŒλ‹€ ν•¨μˆ˜λŠ” λ‹€μŒκ³Ό 같이 μ •μ˜ν•  수 μžˆλ‹€.

add = lambda x, y : x + y
print(add(3, 5)) # 좜λ ₯ : 8

μœ„ μ½”λ“œμ—μ„œ lambda x,y : x+yλŠ” 두 개의 λ§€κ°œλ³€μˆ˜ x와 yλ₯Ό λ°›μ•„ κ·Έ 합을 λ³€ν™˜ν•˜λŠ” λžŒλ‹€ ν•¨μˆ˜μž…λ‹ˆλ‹€. 이λ₯Ό add λ³€μˆ˜μ— ν• λ‹Ήν•˜μ—¬ ν•„μš”ν•  λ•Œ ν˜ΈμΆœν•  수 μžˆλ‹€.

λ‹€ ν•¨μˆ˜μ˜ ν™œμš© 예제

  1. map() ν•¨μˆ˜μ™€ ν•¨κ»˜ μ‚¬μš©ν•˜κΈ°

map() ν•¨μˆ˜λŠ” μ‹œν€€μŠ€ (예 : 리슀트)의 각 μš”μ†Œμ— νŠΉμ • ν•¨μˆ˜λ₯Ό μ μš©ν•˜μ—¬ μƒˆλ‘œμš΄ μ‹œν€€μŠ€λ₯Ό μƒμ„±ν•œλ‹€.

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # 좜λ ₯: [1, 4, 9, 16, 25]

μœ„ μ˜ˆμ œμ—μ„œλŠ” 리슀트 numbers의 각 μš”μ†Œλ₯Ό μ œκ³±ν•˜λŠ” λžŒλ‹€ ν•¨μˆ˜λ₯Ό map()에 μ „λ‹¬ν•˜μ—¬ μƒˆλ‘œμš΄ 리슀트 squaresλ₯Ό μƒμ„±ν•œλ‹€.

  1. filter() ν•¨μˆ˜μ™€ ν•¨κ»˜ μ‚¬μš©ν•˜κΈ°

fliter() ν•¨μˆ˜λŠ” μ‹œν€€μŠ€μ˜ μš”μ†Œ 쀑 νŠΉμ • 쑰건을 λ§Œμ‘±ν•˜λŠ” μš”μ†Œλ§Œ μΆ”μΆœν•˜μ—¬ μƒˆλ‘œμš΄ μ‹œν€€μŠ€λ₯Ό λ§Œλ“ λ‹€.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 좜λ ₯: [2, 4, 6, 8, 10]
  1. μ •λ ¬ μ‹œ key 인자둜 μ‚¬μš©ν•˜κΈ°

리슀트λ₯Ό μ •λ ¬ν•  λ•Œ, key 인자둜 ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ μ •λ ¬ 기쀀을 μ§€μ •ν•  수 μžˆλ‹€.

words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)  # 좜λ ₯: ['date', 'apple', 'banana', 'cherry']

이 μ˜ˆμ œμ—μ„œλŠ” λ‹¨μ–΄μ˜ 길이λ₯Ό κΈ°μ€€μœΌλ‘œ 리슀트λ₯Ό μ •λ ¬ν•œλ‹€.

λžŒλ‹€ ν•¨μˆ˜μ˜ μž₯단점

  • μž₯점
    • κ°„κ²°μ„± : ν•œ μ€„λ‘œ ν•¨μˆ˜λ₯Ό μ •μ˜ν•  수 μžˆμ–΄ μ½”λ“œκ°€ 깔끔해진닀.
    • μΌνšŒμ„± μ‚¬μš© : ν•œ 번만 μ‚¬μš©λ  κ°„λ‹¨ν•œ ν•¨μˆ˜λ₯Ό μ •μ˜ν•  λ•Œ μœ μš©ν•˜λ‹€.
  • 단점
    • μ œν•œλœ κΈ°λŠ₯ : λ³΅μž‘ν•œ λ‘œμ§μ΄λ‚˜ μ—¬λŸ¬ μ€„μ˜ μ½”λ“œλ₯Ό μž‘μ„±ν•  수 μ—†λ‹€.
    • μž¬μ‚¬μš©μ„± λΆ€μ‘± : 이름이 μ—†κΈ° λ•Œλ¬Έμ— μž¬μ‚¬μš©μ„±μ΄ μ–΄λ ΅λ‹€.

λ”°λΌμ„œ, κ°„λ‹¨ν•œ μ—°μ‚°μ΄λ‚˜ λ‹€λ₯Έ ν•¨μˆ˜μ˜ 인자둜 ν•¨μˆ˜λ₯Ό 전달해야 ν•  λ•ŒλŠ” λžŒλ‹€ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜κ³ , λ³΅μž‘ν•œ λ‘œμ§μ΄λ‚˜ μž¬μ‚¬μš©μ΄ ν•„μš”ν•œ κ²½μš°μ—λŠ” def ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ ν•¨μˆ˜λ₯Ό μ •μ˜ν•˜λŠ” 것이 μ’‹λ‹€.

About

✍🏻 [Study] 클래슀 심화, 맀직 λ§€μ†Œλ“œ, μΌκΈ‰ν•¨μˆ˜, 병행성, λ©€ν‹° μŠ€ν¬λž©ν•‘μ— λŒ€ν•œ λ ˆνΌμ§€ν† λ¦¬μž…λ‹ˆλ‹€.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages