解包(Unpacking)
定义
解包是把集合里的元素赋值给变量,封包是把变量构建成元组
任何序列(或者可迭代对象(iterable))都可以通过一个简单的赋值操作来分解为单独的变量
- 示例
>>> x, y = (1, 3)
>>> x
1
>>> y
3
>>> x, y = [1, 3]
>>> x
1
>>> y
3
>>> x, y = y, x
>>> x
3
>>> y
1
>>> head, tail = list(range(0, 10)) # 如果元素个数不匹配,会抛出 ValueError
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-94-551fc62da91b> in <module>()
----> 1 head, tail = list(range(0, 10))
ValueError: too many values to unpack (expected 2)
>>> head, *tail = list(range(0, 10)) # 元素个数匹配
>>> head
0
>>> tail
[1, 2, 3, 4, 5, 6, 7, 8, 9]
解包操作可以用在各种内置结构上,只要对恰好是可迭代的。
列表、元组、字符串、迭代器、生成器等。
*expression来分解包,可以对任意长度的可迭代对象(iterble)中分解元素
>>> head, *tail = [1, 2]
>>> head
1
>>> tail
[2]
>>> head, *tail = [2]
>>> head
2
>>> tail
[]
>>> head, tail = []
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-104-bfd57147ebc5> in <module>()
----> 1 head, tail = []
ValueError: not enough values to unpack (expected 2, got 0)
>>> x = 1, 2, 3
>>> x
(1, 2, 3)
>>> head, *tail = [1, 2, 3]
>>> head
1
>>> tail
[2, 3]
>>> head, *mid, tail = [1, 2, 3, 4, 5]
>>> head
1
>>> mid
[2, 3, 4]
>>> tail
5
在分解操作时,可能想丢弃某些值,可以使用下划线(_),来作为要丢弃值的名称
>>> lst = list(range(0, 10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a, b, _, c, *_ = lst
>>> a
0
>>> b
1
>>> c
3
>>> _
[4, 5, 6, 7, 8, 9]
>>> head, *_, tail = lst
>>> head
0
>>> tail
9
>>> lst = [1, [2, 3], 4]
>>> a, (b, c), d = lst
>>> a
1
>>> b
2
>>> c
3
>>> d
4
>>> lst = [1, [2, 3, 6, 7, 8, 10], 4]
>>> a, (b, *_, c), d = lst
>>> a
1
>>> b
2
>>> d
4
>>> a, b, c, _, *_ = [1, 2, 3, 4, 5, 6]
>>> _
[5, 6]
``

浙公网安备 33010602011771号