这个链分配如何工作? [英] How does this chain assignment work?
问题描述
考虑下面的代码;这是一种糟糕的编程习惯.我想知道为什么结果列表 A
是 [1, 1, 3]
而不是 [1, 2, 1]
.从Java的角度来看,结果应该是[1, 2, 1]
.谁能解释为什么这个结果是这样的?
Consider the following code; it is a bad programming practice. I am wondering why the resulting list A
is [1, 1, 3]
rather than [1, 2, 1]
.
From the view of Java, the result should be [1, 2, 1]
. Can anyone explain why this result is what it is?
A = [1, 2, 3]
t = 2
t = A[t] = A.count(3)
求值后,A是[1, 1, 3]
,t是1
.
我的 Python 版本是 3.3.
My Python version is 3.3.
推荐答案
在第 3 行,您有一个链式作业
On line 3 you have a chained assignment
t = A[t] = A.count(3)
t = A.count(3)
首先评估 - t
设置为 A.count(3)
的返回值,其中在这种情况下是 1.然后将t
(=1)处A
的成员设置为A.count(3)
的返回值,仍然是1.
t = A.count(3)
is evaluated first – t
set to the return value of A.count(3)
which in this case is 1.
Then the member of A
at index t
(=1) is set to the return value of A.count(3)
, which is still 1.
在此处
这篇关于这个链分配如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!