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

查看:25
本文介绍了是否有一种标准化的方法可以在 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.

Python 文档:评估顺序

这意味着表达式 a,b = b,a 的以下内容:

That means the following for the expression a,b = b,a :

  • 右边的b,a被求值,也就是说,在内存中创建了一个包含两个元素的元组.这两个元素是由标识符 ba 指定的对象,它们在程序执行期间遇到指令之前就存在.
  • 刚创建完这个元组之后,还没有对这个元组对象进行赋值,不过没关系,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 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)

这种机制有效地交换了分配给标识符ab

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天全站免登陆