涉及列表索引的 Python 元组分配失败
问题描述
说出清单
s = [1, 2]
我想使用元组分配来编辑列表.为什么这样做很好
and I want to use tuple assignments to edit the list. Why it is fine to do
s[s[0]], s[0] = s[0], s[s[0]] # s == [2, 1]
但不是
s[0], s[s[0]] = s[s[0]], s[0] # get error, index out of range
解决方案
可以在这里.基本上,当您有多个分配时,=
右侧的任何内容都会首先被完全评估.
A good explanation of what is happening under the hood can be found here. Essentially when you have multiple assignments anything to the right of the =
will be fully evaluated first.
让我们以您的第一个示例为例,了解正在发生的事情.
Let’s take your first example and walk through what is happening.
s[s[0]], s[0] = s[0], s[s[0]] # s == [2, 1]
这相当于下面的临时值存储评估的右手边
This is equivalent to the following where temp values store the evaluated right hand sides
# assigns right hand side to temp variables
temp1 = s[0] # 1
temp2 = s[s[0]] # 2
# then assign those temp variables to the left-hand side
s[s[0]] = temp1 # s[1] = 1 —-> s= [1, 1]
s[0] = temp2 # s[0] = 2 —-> s = [2, 1]
如果您遇到索引错误,则会发生以下情况...
In the case you get an index error the following happens...
# assigns right hand side to temp variables
temp1 = s[s[0]] # 2
temp2 = s[0] # 1
# then assign those temp variables to the left-hand side
s[0] = temp1 # s[0] = 2 —-> s= [2, 1]
s[s[0]] = temp2 # s[2] -> Index error (highest index of s is 1)
相关文章