Skip to content

Latest commit

 

History

History
41 lines (27 loc) · 999 Bytes

23.md

File metadata and controls

41 lines (27 loc) · 999 Bytes
@author jackzhenguo
@desc 
@date 2019/2/23

23 交换两元素

理解交换两个元素,需要首先明白什么是pack,什么是unpack

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

# unpack
In [2]: a0,a1 = a                                                               

In [3]: a0                                                                      
Out[3]: 3

In [4]: a1                                                                      
Out[4]: 1

# pack
In [5]: b = a0, a1                                                              

In [6]: b                                                                       
Out[6]: (3, 1)

所以下面 b,a = a,b 交换2个元素的过程,实际是先pack a,b为元组 (a,b),然后再unpack (a,b) 给 b, a的过程

def swap(a, b):
    return b, a


print(swap(1, 0))  # (0,1)
[上一个例子](22.md) [下一个例子](24.md)