Python Extended Unpacking

# Extended Unpacking

기억하면 좋을 것

Left Hand Side(LHS)에서 *의 의미는 보통 우측변에 있는 Iterable을 리스트로 묶어서 취하는 것.
Right Hand Side(RHS)에서 *의 의미는 해당 Iterable의 값을 unpack 하는 것.

s = [1,2,3,4]
*c, = s    # c = [1,2,3,4] --> s를 리스트로 묶어서 취함
c = *s     # c = [*s] --> s를 unpack함


l = [1,2,3,4,5]
a, *b = l # can apply to all iterable even dict/set
l1 = [1,2,3]
l2 = [4,5,6]
l = [*l1, *l2]

set
s1 = "abc"
s2 = "cde"
l = {*s1, *s2} # "a","b","c","d","e"
s1 = {1,2,3}
s2 = {3,4,5}
s3 = {5,6,7}
s4 = {7,8,9}
s = {*s1, *s2, *s3, *s4}

dict
d1 = {"key1":1, "key2":2}
d2= {"key2":3, "key4":4}
{*d1, *d2} ==> {'key2', 'key4', 'key1'}
{**d1, **d2} ==> {'key1': 1, 'key2': 3, 'key4': 4}
{**d2, **d1} ==> {'key2': 2, 'key4': 4, 'key1': 1}
키가 겹치는 경우 나중에 쓰이는 놈의 밸류가 오버로드 된다.

Nested Unpack
a,b,(c,d) = [1,2,"xy"]
l =[1,2,3,4,"pythonic"]
아래 두개의 결과는 같다.
a,b,c,d,e = l[0], l[1:-1], l[-1][0], l[-1][1], l[-1][2:]
a,*b,(c, d,*e) = l

댓글

이 블로그의 인기 게시물

로컬 Tomcat 서버 실행속도 개선

2019.05.23 - SQLAlchemy 의 객체 상태 관리 (expire, refresh, flush, commit) 에 관한 이해

2020.02.17 Python의 multiprocessing 중 Pool.map(), chunksize에 관한 내용