为什么这个python代码给出了[3,3]?

时间:2017-03-13 12:23:07

标签: python list pop

考虑一下这段代码?

var config = {
    authority: "http://localhost:5000",
    client_id: "js",
    redirect_uri: "http://localhost:5003/callback.html",
    response_type: "id_token token",
    scope:"openid profile api1",  <--- REMOVE API1 HERE 
    post_logout_redirect_uri : "http://localhost:5003/index.html",
};
var mgr = new Oidc.UserManager(config);

这会给b = [[5], [3]] a = b[1] b[-1] += b.pop() print(a)

您无法通过将[3,3]展开到b[-1] += b.pop()来解释它。

为什么会得到这个输出?

3 个答案:

答案 0 :(得分:6)

因为如果您使用b[-1],则只会提取第二个列表的引用,然后操作+=完成,最后将其存储回列表 。所以b[-1] += b.pop()基本上等同于:

tmp = b[-1]  # tmp = [3]
tmp += b.pop() # tmp = [3,3], b = [[5]]
b[-1] = tmp # tmp = [3,3], b = [[3,3]]

(但当然有tmp,上面的片段是在翻译层完成的)

现在tmp refence b中的第二个列表(所以tmp is a)。因此,这意味着您使用a扩展 inplace b.pop()b.pop()[3]。那么你所做的就是用tmp扩展[3](当时为tmp)。因此tmp(因此a变为[3,3])。所以b现在是[[3,3]]

请注意x += y list不等同于x = x+y 。实际上,如果你编写代码如下:

>>> a = [1]
>>> b = a
>>> b = b + [2]
>>> print(a,b)
[1] [1, 2]

这将不更新a (因为它未完成 inplace )。鉴于:

>>> a = [1]
>>> b = a
>>> b += [2]
>>> print(a,b)
[1, 2] [1, 2]

将导致ab同时为[1,2]。当然,通常+=应该像添加一样,但添加是在 inplace 中完成的,这可能会产生一些影响。

答案 1 :(得分:0)

在打印之前尝试打印b [-1]。 b [-1]指b中的最后一个元素,您要添加另一个元素。这似乎发生了,因为当你执行a = b[1]时,它必须通过引用分配,因为当更新b [1](在这种情况下与b [-1]相同)时更新。

答案 2 :(得分:0)

首先,列表b中只有2个元素。

b = [[5], [3]]
a = b[1]

print b[1] 
# gives [3]
print b[-1] 
# also gives [3] because here -1 refers to the last element and there are 
# only two elements.

b[-1] += b.pop()
# here you are appending 3 to [3] of b

print b[-1] 
print a
# that is why when you print a it gives [3,3] as the b[1] value was 
# appended to a in the second step itself and you are just printing here.

希望你得到我想说的话。