Python lambda, sort ν¨μ
lambda, sort ν¨μμ λν΄ μ΄ν΄ν΄λ³΄κΈ°
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)]