是否有一种标准化的方法可以在 Python 中交换两个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14836228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a standardized method to swap two variables in Python?
提问by WilliamKF
In Python, I've seen two variable values swapped using this syntax:
在 Python 中,我已经看到使用以下语法交换了两个变量值:
left, right = right, left
Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?
这是否被认为是交换两个变量值的标准方法,还是有其他一些方法可以让两个变量按照惯例最常交换?
采纳答案by eyquem
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
http://docs.python.org/3/reference/expressions.html#evaluation-order
Python 从左到右计算表达式。请注意,在评估赋值时,右侧先于左侧进行评估。
http://docs.python.org/3/reference/expressions.html#evaluation-order
That means the following for the expression a,b = b,a:
这意味着表达式a,b = b,a如下:
- the right-hand side
b,ais evaluated, that is to say a tuple of two elements is created in the memory. The two element are the objects designated by the identifiersbanda, that were existing before the instruction is encoutered during an execution of program - just after the creation of this tuple, no assignement of this tuple object have still been made, but it doesn't matter, Python internally knows where it is
- then, the left-hand side is evaluated, that is to say the tuple is assigned to the left-hand side
- as the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier
abe assigned to the first element of the tuple (which is the object that was formely bbefore the swap because it had nameb)
and the second identifierbis assigned to the second element of the tuple (which is the object that was formerly abefore the swap because its identifiers wasa)
- 右侧
b,a被评估,也就是说在内存中创建了一个由两个元素组成的元组。这两个元素是由标识符b和指定的对象a,它们在程序执行期间遇到指令之前就已存在 - 刚创建完这个元组之后,还没有对这个元组对象进行赋值,不过没关系,Python内部知道它在哪里
- 然后,左侧被评估,也就是说元组被分配到左侧
- 由于左侧由两个标识符组成,元组被解包,以便将第一个标识符
a分配给元组的第一个元素(它是在交换之前以前是b的对象,因为它有 nameb)
和第二个标识符b被分配给元组的第二个元素(这是在交换之前以前是 a的对象,因为它的标识符是a)
This mechanism has effectively swapped the objects assigned to the identifiers aand b
这种机制有效地交换了分配给标识符的对象a和b
So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.
因此,要回答您的问题:是的,这是在两个对象上交换两个标识符的标准方法。
顺便说一下,对象不是变量,它们是对象。
回答by Martijn Pieters
That is the standard way to swap two variables, yes.
这是交换两个变量的标准方法,是的。
回答by NoOneIsHere
I know three ways to swap variables, but a, b = b, ais the simplest. There is
我知道三种交换变量的方法,但这a, b = b, a是最简单的。有
XOR (for integers)
XOR(对于整数)
x = x ^ y
y = y ^ x
x = x ^ y
Or concisely,
或者简而言之,
x ^= y
y ^= x
x ^= y
Temporary variable
临时变量
w = x
x = y
y = w
del w
Tuple swap
元组交换
x, y = y, x
回答by Yi Huang
I would not say it is a standard way to swap because it will cause some unexpected errors.
我不会说这是交换的标准方式,因为它会导致一些意外错误。
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
nums[i]will be modified first and then affect the second variable nums[nums[i] - 1].
nums[i]将首先被修改然后影响第二个变量nums[nums[i] - 1]。
回答by gizzmole
Does not work for multidimensional arrays, because references are used here.
不适用于多维数组,因为此处使用了引用。
import numpy as np
# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)
# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)
See also Swap slices of Numpy arrays
另请参阅交换 Numpy 数组的切片
回答by LogicalBranch
To get around the problems explained by eyquem, you could use the copymodule to return a tuple containing (reversed) copies of the values, via a function:
要解决eyquem解释的问题,您可以使用该copy模块通过函数返回包含(反向)值副本的元组:
from copy import copy
def swapper(x, y):
return (copy(y), copy(x))
Same function as a lambda:
与 a 相同的功能lambda:
swapper = lambda x, y: (copy(y), copy(x))
Then, assign those to the desired names, like this:
然后,将它们分配给所需的名称,如下所示:
x, y = swapper(y, x)
NOTE:if you wanted to you could import/use deepcopyinstead of copy.
注意:如果你愿意,你可以导入/使用deepcopy而不是copy.
回答by u-betcha
You can combine tupleand XORswaps: x, y = x ^ x ^ y, x ^ y ^ y
您可以组合元组和XOR交换:x, y = x ^ x ^ y, x ^ y ^ y
x, y = 10, 20
print('Before swapping: x = %s, y = %s '%(x,y))
x, y = x ^ x ^ y, x ^ y ^ y
print('After swapping: x = %s, y = %s '%(x,y))
or
或者
x, y = 10, 20
print('Before swapping: x = %s, y = %s '%(x,y))
print('After swapping: x = %s, y = %s '%(x ^ x ^ y, x ^ y ^ y))
Using lambda:
使用lambda:
x, y = 10, 20
print('Before swapping: x = %s, y = %s' % (x, y))
swapper = lambda x, y : ((x ^ x ^ y), (x ^ y ^ y))
print('After swapping: x = %s, y = %s ' % swapper(x, y))
Output:
输出:
Before swapping: x = 10 , y = 20
After swapping: x = 20 , y = 10

