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 元组分配失败


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01