>>>p=(4,5)>>>x,y=p>>>x4>>>y5>>>>>>data=['ACME',50,91.1,(2012,12,21)]>>>name,shares,price,date=data>>>name'ACME'>>>date(2012, 12, 21)>>>name,shares,price,(year,mon,day)=data>>>name'ACME'>>>year2012>>>mon12>>>day21>>>
요소수에 불일치가 있으면 에러가 난다는 것에 주의하자.
>>>p=(4,5)>>>x,y,z=pTraceback (most recent call last):File"<stdin>", line1, in<module>ValueError:need more than 2 values to unpack>>>
변수에 대한 Unpacking은 튜플이나 리스트에 국한되는것이 아님.
여기는 문자열, 파일 및 이터레이터와 제너레이터가 포함됨.
>>>s='Hello'>>>a,b,c,d,e=s>>>a'H'>>>b'e'>>>e'o'>>>
unpacking을 시도중 분명히 버리고 싶은 값이 있을 수도 있음.
그럴때는 _를 사용해서 버려주면 된다.
>>>data=['ACME',50,91.1,(2012,12,21)]>>>_,shares,price,_=data>>>shares50>>>price91.1>>>
'Python > Python Cookbook' 카테고리의 다른 글
| [Python] 마지막 N개의 요소를 유지하고 싶다면 (0) | 2017.02.16 |
|---|---|
| [Python] 임의의 길이의 요소 Unpacking (0) | 2017.02.16 |

