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
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM