任何可迭代对象(列表、元祖、字符串、文件对象、迭代器和生成器等),都可以通过一个简单的赋值语句拆包并赋值给多个变量,但是要保证变量的数量和可迭代对象元素的数量一致。
1. 常见写法
>>> p = (1, 2) >>> x, y = p >>> x 1 >>> y 2 >>> >>> data = [ clip, 23, 172, (2018, 10, 22) ] >>> name, age, height, birth= data >>> name clip >>> birth (2018, 10, 22) >>> name, age, height, (year, mon, day) = data >>> name clip >>> year 2018 >>> mon 10 >>> day 22 >>>
2. 对不需要的元素进行占位
>>> data = [ 'clip', 23, 172, (2018, 10, 22) ] >>> _, age, height, _ = data >>> age 23 >>> height 172 >>> *_, height, birth = data >>> height 172 >>> birth (2018, 10, 22) >>> name, *_, (*_, day) = data >>> name 'clip' >>> day 22 >>>