1 ๋ถ„ ์†Œ์š”

Lambda์— ๋Œ€ํ•ด์„œโ€ฆ

1. Lambda๋ž€

Lambda๋ž€ ์˜๋ฏธ ์ต๋ช…ํ•จ์ˆ˜๋ฅผ ์ง€์นญํ•˜๋Š” ์šฉ์–ด ์ฆ‰, ๊ธฐ์กด์˜ ํ•จ์ˆ˜(๋ช… ๋“ฑ)์„ ์„ ์–ธํ•˜๊ณ  ์‚ฌ์šฉํ•˜๋˜ ๋ฐฉ์‹๊ณผ๋Š” ๋‹ฌ๋ฆฌ ๋ฐ”๋กœ ์ •์˜ํ•˜์—ฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๋ฅผ ๋œปํ•œ๋‹ค.

1.2. ํ˜•์‹

ํ˜•์‹์€ ์–ด๋–ป๊ฒŒ ๋ ๊นŒ?
lambda ์ธ์ž : ํ‘œํ˜„์‹๊ณผ ๊ฐ™์ด ๋‚˜ํƒ€๋‚ธ๋‹ค.

lambda x : x+1

1.3. ์ธ์ž ๋ถ€์—ฌ

์ธ์ž๋Š” ์–ด๋–ป๊ฒŒ ๋„ฃ์–ด?
๋žŒ๋‹ค ํ‘œํ˜„์‹์„ ๊ด„ํ˜ธ๋กœ ๋ฌถ์€ ๋’ค์— ๋‹ค์‹œ ๊ด„ํ˜ธ๋ฅผ ๋ถ™์ด๊ณ  ์ธ์ˆ˜๋ฅผ ๋„ฃ์–ด ํ˜ธ์ถœํ•œ๋‹ค.
[์˜ˆ์‹œ]

(lambda x: x + 1)(1)
> 2

1.4. ์ธ์ž 2๊ฐœ

์ธ์ž๋ฅผ ๋‘๊ฐœ ์‚ฌ์šฉํ•ด๋ณด์ž!

lambda x,y: x+y

1.5. if๋ฌธ ์‚ฌ์šฉ

if๋ฌธ๋„ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค!

check_pass = lambda x: 'pass' if x>=70 else 'fail'

2. ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž

key ์ธ์ž๋ฅผ ์ •ํ•˜์ง€ ์•Š์€ ๊ธฐ๋ณธ์ ์ธ sort์—์„ , ํŠœํ”Œ ์ˆœ์„œ๋Œ€๋กœ ์šฐ์„ ์ˆœ์œ„ ๊ธฐ๋ณธ ํ• ๋‹น

a = [(1, 2), (5, 1), (0, 1), (5, 2), (3, 0)]

# ์•ž์˜ ์ธ์ž๋กœ ์ •๋ ฌ๋จ
b = sorted(a)
b = [(0, 1), (1, 2), (3, 0), (5, 1), (5, 2)]

key ์ธ์ž์— ํ•จ์ˆ˜๋ฅผ ๋„˜๊ฒจ์ฃผ๋ฉด ์šฐ์„ ์ˆœ์œ„๊ฐ€ ์ •ํ•ด์ง.

c = sorted(a, key = lambda x : x[0]) 

c = [(0, 1), (1, 2), (3, 0), (5, 1), (5, 2)]

d = sorted(a, key = lambda x : x[1]) 

d = [(3, 0), (5, 1), (0, 1), (1, 2), (5, 2)]

3. map ๋žŒ๋‹ค ํ‘œํ˜„์‹

map์œผ๋กœ๋„ ๋žŒ๋‹ค ํ‘œํ˜„์‹์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

list(map(lambda x: x+10, [1,2,3]))

> [11, 12, 13]

4. filter()

filter()์— ๋žŒ๋‹ค ํ‘œํ˜„์‹์„ ์‚ฌ์šฉํ•˜๋ฉด True๊ฐ’๋งŒ ๋ฐ˜ํ™˜ํ•จ!

a = [8, 4, 2, 5, 2, 7, 9, 11, 26, 13]

result = list(filter(lambda x : x > 7 and x < 15, a))

> [8, 9, 11, 13]

5. reduce() ํ‘œํ˜„์‹

reduce()๋Š” ๊ฐ’์„ ๋ˆ„์ ์‹œํ‚จ๋‹ค.

from functools import reduce t = [47, 11, 42, 13]

result = reduce(lambda x, y : x + y, t)

> 113

์ฐธ๊ณ : reduce()๋Š” functools ๋ชจ๋“ˆ์„ ๋ถˆ๋Ÿฌ์™€์„œ ์‚ฌ์šฉํ•˜์ž

6. ์˜ˆ์ œ

  1. ์ˆซ์ž ํฌ๊ธฐ๋Œ€๋กœ ์ •๋ ฌ

์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•˜์ž.

data = [
    ["๊ณ ๊ตฌ๋งˆ",25000],
    ["๋ฐ”๋‚˜๋‚˜",123232],
    ["ํŒŒ์ธ์• ํ”Œ",4500],
    ["๊ฐ์ž",3000],
    ["๊ธˆ๊ทค",6000]
]

๊ฐ€๊ฒฉ์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๋ฉด

data.sort(key = lambda x:x[1])
print(data)
## ์ถœ๋ ฅ ๊ฐ’ 
#[['๊ฐ์ž', 3000], ['ํŒŒ์ธ์• ํ”Œ', 4500], ['๊ธˆ๊ทค', 6000], ['๊ณ ๊ตฌ๋งˆ', 25000], ['๋ฐ”๋‚˜๋‚˜', 123232]]
  1. ๋‹จ์–ด ์‚ฌ์ „ ์ˆœ ์ •๋ ฌ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•˜์ž.
    data = ["๋‚˜๋ผ","๊ฐ€๊ตฌ","๋ด„","๊ฐ€์„","๋„ํ† ๋ฆฌ","๋‚ซ","ํ˜น","๊ฐ€์„ ์•„์นจ","๋‚˜๋Š” ๋ฐฅ์„ ๋จน๊ณ  ์žˆ๋‹ค."]
    

    ๋‹จ์–ด์˜ ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋ฉด
    ```python data.sort(key = lambda x:(len(x),x))

print(data) ```

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ:

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ