python实现同时给多个变量赋值的方法 Simultaneous Assignments

Simultaneous Assignments

x,y=y,x

这个赋值的执行流程是什么?

python的多元赋值原理是tuple的元组封装 (tuple packing) 和 序列拆封(sequence unpacking)。

t = 12345, 54321, 'hello!'

这是元组封装 (tuple packing) 的例子,将多个值放进tuple里。

x, y, z = t

元组封装 (tuple packing) 的逆操作就是序列拆封(sequence unpacking)。这个调用等号右边可以是任何线性序列,序列拆封要求左侧的变量数目与序列的元素个数相同。

多元赋值变量交换的例子:

a, b = b, a

就是将(b, a)打包成元祖,再序列的分给(a, b)这个序列。

 

官方文档:

http://www.pythondoc.com/pythontutorial3/datastructures.html#tut-tuples

Python tutorial 2.7.13 2.7.13 documentation

 
REF
 
http://www.pythondoc.com/pythontutorial27/datastructures.html#tut-tuples
http://www.pythondoc.com/pythontutorial3/datastructures.html#tut-tuples
https://www.zhihu.com/question/46505057/answer/101584055
 
原文地址:https://www.cnblogs.com/emanlee/p/15210785.html