Python Tuple Assignment involving list index failed(涉及列表索引的 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 元组分配失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:涉及列表索引的 Python 元组分配失败


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01