在Python中,我看到过使用这种语法交换的两个变量值:

left, right = right, left

这被认为是交换两个变量值的标准方法吗?还是有其他方法可以使两个变量按惯例交换?


当前回答

我不会说这是交换的标准方式,因为它会导致一些意想不到的错误。

nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]

首先修改Nums [i],然后影响第二个变量Nums [Nums [i] - 1]。

其他回答

为了解决eyquem解释的问题,你可以使用copy模块通过函数返回一个包含(反向)值副本的元组:

from copy import copy

def swapper(x, y):
  return (copy(y), copy(x))

与lambda相同的函数:

swapper = lambda x, y: (copy(y), copy(x))

然后,将它们分配给所需的名称,如下所示:

x, y = swapper(y, x)

注意:如果你想,你可以导入/使用deepcopy而不是copy。

你可以结合元组和异或交换:x, y = x ^ x ^ y x ^ 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))

使用λ:

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))

输出:

Before swapping: x =  10 , y =  20
After swapping: x =  20 , y =  10

这是交换两个变量的标准方法。

Python从左到右计算表达式。注意,当 求赋值时,右边在 左手边。 Python文档:计算顺序

这意味着表达式a,b = b,a:

The right-hand side b,a is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during the execution of the program. Just after the creation of this tuple, no assignment of this tuple object has 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 a be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b) and the second identifier b is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a)

这种机制有效地交换了分配给标识符a和b的对象

所以,回答你的问题:是的,这是在两个对象上交换两个标识符的标准方式。 顺便说一下,对象不是变量,它们是对象。

我知道三种交换变量的方法,但a, b = b, a是最简单的。有

异或(整数)

x = x ^ y
y = y ^ x
x = x ^ y

或简洁,

x ^= y
y ^= x
x ^= y

临时变量

w = x
x = y
y = w
del w

元组交换

x, y = y, x