lambda ν‘œν˜„μ‹

lambda x: (x)

lambdaλŠ” ν•¨μˆ˜μ˜ μ„ μ–Έμ΄λ‚˜ μ‹λ³„μž 없이 ν•˜λ‚˜μ˜ μ‹μœΌλ‘œ ν•¨μˆ˜λ₯Ό ν‘œν˜„ν•˜λŠ” 방법이닀 λ‹€μŒμ˜ ν•¨μˆ˜λŠ”

def func(x, y):
    return x + y

μ•„λž˜μ™€ 같이 λžŒλ‹€ ν‘œν˜„μ‹μœΌλ‘œ ν‘œν˜„ν•  수 μžˆλ‹€.

lambda x, y: x + y

lambda μ˜ˆμ‹œ

lambda x: x + 1 # λ³€μˆ˜ 1개
lambda x: (x + 1)(1) # κ΄„ν˜Έλ‘œ λ³€μˆ˜ κ°’ μ£ΌκΈ°
lambda x, y: x + y # λ³€μˆ˜ 2개

sort ν•¨μˆ˜

sort()

sort ν•¨μˆ˜λ₯Ό ν†΅ν•΄μ„œ 리슀트λ₯Ό μ •λ ¬ ν•  수 μžˆλ‹€.

a = [2, 3, 5, 4, 1]
a.sort()
print(a) // a = [1, 2, 3, 4, 5]

sort(key = func)

sort ν•¨μˆ˜μ˜ key 인자λ₯Ό μ‚¬μš©ν•΄μ„œ μ •λ ¬ 기쀀을 μ œκ³΅ν•΄μ€„ 수 μžˆλ‹€.

a = [(0, 1), (1, 5), (2, 3), (1, 2)]
a.sort(key=lambda x: x[0] # νŠœν”Œ aλ₯Ό μ •λ ¬ν•˜λŠ”λ° (x, y) 쀑 x κΈ°μ€€ μ •λ ¬
print(a)
# [(0, 1), (1, 5), (1, 2), (2, 3)] 좜λ ₯

μ΄λ•Œ key μΈμžμ— λ‘λ²ˆμ§Έ 값을 ν†΅ν•΄μ„œ 같은 μš°μ„  μˆœμœ„μΈ κ°’λ“€μ˜ λ‘λ²ˆμ§Έ 기쀀을 μ œκ³΅ν•΄μ€„ 수 μžˆλ‹€.

a = [(0, 1), (1, 5), (2, 3), (1, 2)]
a.sort(key=lambda x: (x[0], x[1]))
print(a)
#[(0, 1), (1, 2), (1, 5), (2, 3)]
a.sort(key=lambda x: (x[0], -x[1]))# -λŠ” λ‚΄λ¦Όμ°¨μˆœ
print(a)
#[(0, 1), (1, 5), (1, 2), (2, 3)]