本文介绍了涉及列表索引的 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)
这篇关于涉及列表索引的 Python 元组分配失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!