内置数据结构-封包解包

解包,个人理解就是对序列进行拆分,赋值给对应的变量
最经典的莫过于两个数交换,一般我们是通过一个中间变量把两个数交换,在python中可以直接通过解包的形式直接交换两个数
如:

In [92]: a,b=1,3

In [93]: a
Out[93]: 1

In [94]: b
Out[94]: 3

In [96]: a,b=3,1

In [97]: a
Out[97]: 3

In [98]: b
Out[98]: 1

In [99]: 

其实 a, b = 1, 3 就是 a, b = (1, 3), 把序列中对应的元素赋值给a,b
再看一组例子

In [99]: head, *tail = [1,2,3,4,5]

In [100]: head
Out[100]: 1

In [101]: tail
Out[101]: [2, 3, 4, 5]

In [104]: head, *_, tail = [1,2,3,4,5]

In [105]: head
Out[105]: 1

In [106]: tail
Out[106]: 5

In [107]: _
Out[107]: 5

In [108]: head, *mid, tail = [1,2,3,4,5]

In [109]: mid
Out[109]: [2, 3, 4]

In [120]: head, _, *mid, tail = [1,2,3,4,5]

In [121]: head
Out[121]: 1

In [122]: mid
Out[122]: [3, 4]

In [123]: tail
Out[123]: 5


In [115]: h, *t = ['a']

In [116]: h
Out[116]: 'a'

In [117]: t
Out[117]: []


In [124]: a, (b, c), d = [1, [2,3],4]

In [125]: a
Out[125]: 1

In [126]: b
Out[126]: 2

In [127]: c
Out[127]: 3

In [128]: d
Out[128]: 4

从上面可以感受到解包的强大之处,如果元素个数有多个,想解包后放在一个变量里面就要使用*变量名_用作变量名时表示丢弃这些变量,python中单个_表示上一个命令的返回值,*变量名解包后都是一个列表

封包

封包就是把多个元素打包赋值给一个变量,函数中返回多个值就是一个封包

In [118]: v = 1,2,3

In [119]: v
Out[119]: (1, 2, 3)

你可能感兴趣的:(内置数据结构-封包解包)