Why does this iterative list-growing code give IndexError: list assignment index out of range?(为什么这个迭代的列表增长代码会给出 IndexError: list assignment index out of range?)
问题描述
请考虑以下代码:
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
print j
输出(Win 7 32 位上的 Python 2.6.6)是:
The output (Python 2.6.6 on Win 7 32-bit) is:
> Traceback (most recent call last):
> j[k] = l IndexError: list assignment index out of range
我想这很简单,我不明白.有没有大佬可以解惑?
I guess it's something simple I don't understand. Can someone clear it up?
推荐答案
j
是一个空列表,但您正试图写入元素 [0]
中第一次迭代,尚不存在.
j
is an empty list, but you're attempting to write to element [0]
in the first iteration, which doesn't exist yet.
尝试以下方法,将新元素添加到列表末尾:
Try the following instead, to add a new element to the end of the list:
for l in i:
j.append(l)
当然,如果您只想复制现有列表,那么您在实践中永远不会这样做.你只需这样做:
Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:
j = list(i)
或者,如果您想像使用其他语言中的数组一样使用 Python 列表,则可以预先创建一个列表,并将其元素设置为空值(以下示例中的 None
),然后覆盖特定位置的值:
Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None
in the example below), and later, overwrite the values in specific positions:
i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0
for l in i:
j[k] = l
k += 1
要意识到的是,list
对象不允许您为不存在的索引分配值.
The thing to realise is that a list
object will not allow you to assign a value to an index that doesn't exist.
这篇关于为什么这个迭代的列表增长代码会给出 IndexError: list assignment index out of range?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个迭代的列表增长代码会给出 IndexErro


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