### Unpacking Arguments in Python
def foo(x, y, z):
print(x, y, z)
def mySum(*args):
return sum(args)
def main():
ls = [1, 2, 3]
# Unpacking list into three arguments
foo(*ls)
print('\t')
print(list(range(3, 6)))
print('\t')
args = [3, 6]
print(list(range(*args)))
print('\t')
print(mySum(1, 2, 3, 4, 5))
print('\t')
# unpacking of dictionary items using **
d = {'x':2, 'y':4, 'z':10}
foo(**d)
if __name__ == '__main__':
main()
#결과
1 2 3
[3, 4, 5]
[3, 4, 5]
15
2 4 10
# 튜플 언패킹
t1, t2, t3 = 1, 2, 3
print(t1, t2, t3)
print("")
# 리스트 언패킹
t4, t5, t6 = [4, 5, 6]
print(t4, t5, t6)
print("")
# 함수 인자 언패킹
t0 = [0, 0, 0]
print(*t0,"/", t0) # 단순 리스트 출력과 비교
# 결과
1 2 3
4 5 6
0 0 0 / [0, 0, 0]
# Unpacking of dictionary (Single-ine unpackin)
# key만 언패킹 된다.
t, c = {'Texas': 1, 'California': 50}
print(t, c)
# 결과
Texas California
# Partial Unpacking with Star Notation
data = 1, 2, 3, 4, 5
a, *b = data
print(f"a, *b => {a}, {b}")
*x, y = data
print(f"*x, y => {x}, {y}")
q, *w, e = data
print(f"q, *w, e => {q}, {w}, {e}")
# 결과
a, *b => 1, [2, 3, 4, 5]
*x, y => [1, 2, 3, 4], 5
q, *w, e => 1, [2, 3, 4], 5
# Unpacking
x, y = 10, 20
print(f"{x=}, {y=}")
a, b = [1, 2]
print(f"{a=}, {b=}")
s, o = "SO"
print(f"{s=}, {o=}")
s, *o = "SOSIMPLE"
print(f"{s=}, {o=}")
s, *o, m = "SOSIMPLE"
print(f"{s=}, {o=}, {m=}")
*_, last = '1234567890'
print(f"{last=}")
print(f"{_=}")
# dict unpacking
def add(a: int, b: int) -> int:
print(f"{a+b = }")
numbers: dict[str, int] = {'a': 5, 'b': 10}
add(**numbers)
numbers: list[int] = [1, 2, 3, 4, 5]
param: dict[str, str] = {'sep': '-', 'end': '.'}
print(*numbers, **param)
# 결과
x=10, y=20
a=1, b=2
s='S', o='O'
s='S', o=['O', 'S', 'I', 'M', 'P', 'L', 'E']
s='S', o=['O', 'S', 'I', 'M', 'P', 'L'], m='E'
last='0'
_=['1', '2', '3', '4', '5', '6', '7', '8', '9']
a+b = 15
1-2-3-4-5.
댓글 영역