Home  >  Article  >  Backend Development  >  Python中变量交换的例子

Python中变量交换的例子

WBOY
WBOYOriginal
2016-06-16 08:42:311105browse

Python追求简洁,诞生不少运算赋值规则,力求从简,其中就包括两个或者多个变量交换值。
普通语言中

复制代码 代码如下:

# 声明变量
a=50
b=10
# 开始交换,先把其中一个值赋给临时变量,然后才能实现交换变量。
tmp = a
a = b
b = tmp

在Python中,实现两个变量值交换非常方便
复制代码 代码如下:

# 声明变量
a=50
b=10
# 开始交换变量
a,b = b,a

甚至可以多个变量同时交换
复制代码 代码如下:

a=50
b=10
c=20
c,b,a = a,b,c

一个运算符就搞定多个变量值互换!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn