λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
IT-Engineering/Python

파이썬 *(λ³„ν‘œ) μ—°μ‚°μžλ‘œ 리슀트 μ—΄κ±°ν•˜κΈ°(feat. κ°€λ³€μΈμž ν•¨μˆ˜)

by 🧞‍♂️ 2020. 5. 26.
λ°˜μ‘ν˜•

2020/05/26 - [IT-Engineering/Python] - 파이썬 κ°€λ³€μΈμž ν•¨μˆ˜ μ •μ˜ μ˜ˆμ‹œ

 

파이썬 κ°€λ³€μΈμž ν•¨μˆ˜ μ •μ˜ μ˜ˆμ‹œ

νŒŒμ΄μ¬μ—μ„œ ν•¨μˆ˜μ˜ 인자λ₯Ό κ°€λ³€μΈμžλ‘œ μ£ΌκΈ° μœ„ν•΄μ„œλŠ” 인자 μ•žμ— *μ—°μ‚°μžλ§Œ 적어주면 λœλ‹€. λ‹€μŒμ˜ μ˜ˆμ‹œλ§Œ 이해할 수 μžˆλ‹€λ©΄, μ‰½κ²Œ 적용 κ°€λŠ₯ν•  것이닀. def sum(*args): result = 0 for i in args: result += i r

gentlesark.tistory.com

μœ„μ˜ κ°€λ³€μΈμž ν•¨μˆ˜μ—μ„œλ„ *(λ³„ν‘œ) μ—°μ‚°μžλ₯Ό μ΄μš©ν•˜μ—¬ κ°€λ³€μΈμžλ₯Ό μ •μ˜ν–ˆμ—ˆλŠ”λ°,

μ΄λ²ˆμ—λŠ” λ¦¬μŠ€νŠΈμ—μ„œ *(λ³„ν‘œ) μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•΄μ„œ 리슀트λ₯Ό 해체 ν˜Ήμ€ μ—΄κ±°ν•˜μ—¬ κ°€λ³€μΈμž ν•¨μˆ˜μ— μ§‘μ–΄λ„£λŠ” μ˜ˆμ‹œλ₯Ό 보이겠닀.

def sum(*args):
    result = 0
    for i in args:
        result += i
    return result

res = sum(1,2,3,4,5)
print(res)
# output: 15

anylist = [1,2,3,4,5]
res2 = sum(*anylist)
print(res2)
# output: 15

# res3 = sum(anylist) # ERROR!

μœ„μ˜ 9λΌμΈκΉŒμ§€κ°€ 맨 μœ„μ— 링크된 κ°€λ³€μΈμž ν•¨μˆ˜μ˜ ν˜•νƒœμΈλ°,

μ•„λž˜ 12λΌμΈμ—μ„œ anylist에 *연산을 μˆ˜ν–‰ν•˜λ©΄ 리슀트 λ‚΄λΆ€μ˜ 값듀이 κ°€λ³€μΈμžλ‘œ μœ„μ—μ„œ sum(1,2,3,4,5)λ₯Ό ν•΄μ€€ νš¨κ³Όμ™€ κ°™κ²Œλœλ‹€.

listλ₯Ό κ·ΈλŒ€λ‘œ λ„£μœΌλ©΄ μ–΄λ–»κ²Œ λ˜λƒκ³ ?

맨 λ§ˆμ§€λ§‰ 쀄을 μ£Όμ„μ²˜λ¦¬ ν•΄μ œν•΄μ„œ λŒλ €λ³΄μ‹œλΌ. λ‹€μŒκ³Ό 같은 μ—λŸ¬κ°€ λ‚  것이닀.

λ°˜μ‘ν˜•

λŒ“κΈ€