在Python中,我看到两个变量值使用以下语法交换:

left, right = right, left

这是否被认为是交换两个变量值的标准方式,或者按照惯例,是否有其他方式最常交换两个变量?

推荐答案

Python从左到右计算表达式.注意

Python docs: Evaluation order

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

  • 对右侧b,a求值,也就是说,在存储器中创建两个元素的元组.这两个元素是在程序执行期间遇到指令之前存在的由标识符ba指定的对象.
  • 就在创建这个元组之后,仍然没有对这个元组对象进行赋值,但是这并不重要,Python内部知道它在哪里.
  • 然后,计算左侧,也就是说,将元组分配给左侧.
  • 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的对象

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相关问答推荐

在函数内部使用eval(),将函数的输入作为字符串的一部分

如何使用Jinja语法在HTML中重定向期间传递变量?

运行Python脚本时,用作命令行参数的SON文本

有症状地 destruct 了Python中的regex?

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

更改键盘按钮进入'

numpy卷积与有效

为什么抓取的HTML与浏览器判断的元素不同?

在pandas中使用group_by,但有条件

Pandas Loc Select 到NaN和值列表

从嵌套的yaml创建一个嵌套字符串,后面跟着点

索引到 torch 张量,沿轴具有可变长度索引

Django—cte给出:QuerySet对象没有属性with_cte''''

pandas:对多级列框架的列进行排序/重新排序

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

提取数组每行的非零元素

随机森林n_估计器的计算

PYTHON中的selenium不会打开 chromium URL

Python:使用asyncio.StreamReader.readline()读取长行