在Python中,我看到两个变量值使用以下语法交换:
left, right = right, left
这是否被认为是交换两个变量值的标准方式,或者按照惯例,是否有其他方式最常交换两个变量?
在Python中,我看到两个变量值使用以下语法交换:
left, right = right, left
这是否被认为是交换两个变量值的标准方式,或者按照惯例,是否有其他方式最常交换两个变量?
Python从左到右计算表达式.注意
对于表达式a,b = b,a
,这意味着以下内容:
b,a
求值,也就是说,在存储器中创建两个元素的元组.这两个元素是在程序执行期间遇到指令之前存在的由标识符b
和a
指定的对象.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
)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
的对象
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.