是否有标准化的方法可以在Python中交换两个变量? [英] Is there a standardized method to swap two variables in Python?

查看:127
本文介绍了是否有标准化的方法可以在Python中交换两个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我已经看到使用此语法交换了两个变量值:

In Python, I've seen two variable values swapped using this syntax:

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?

推荐答案


Python从左到右计算表达式。请注意,在
评估作业时,右侧的评估在
左侧的评估之前。

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

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


  • 对右侧 b,a 进行评估,即也就是说在内存中创建了两个元素的元组。这两个元素是由标识符 b a 所指定的对象,这些对象在指令执行过程中被加密之前就已存在。程序的执行

  • 仅在创建该元组之后,仍未分配该元组对象,但这没关系,Python内部知道它在哪里

  • 然后,评估左侧,也就是说,将元组分配给左侧

  • ,因为组成了左侧在两个标识符中,对元组进行解压缩,以便将第一个标识符 a 分配给元组的第一个元素(该对象以前是 b ,因为它的名称为 b

    和第二个标识符 b
  • 分配给元组的第二个元素(该对象是交换之前的 a 对象,因为其标识符为 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 element are the objects designated by the identifiers b and a, 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 a be assigned to the first element of the tuple (which is the object that was formely 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

This mechanism has effectively swapped the objects assigned to the identifiers a and 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.

这篇关于是否有标准化的方法可以在Python中交换两个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆