【发布时间】:2013-03-27 07:47:29
【问题描述】:
我正在尝试在 Python 中设置数组的索引,但它没有按预期运行:
theThing = []
theThing[0] = 0
'''Set theThing[0] to 0'''
这会产生以下错误:
Traceback (most recent call last):
File "prog.py", line 2, in <module>
theThing[0] = 0;
IndexError: list assignment index out of range
在 Python 中设置数组索引的正确语法是什么?
【问题讨论】:
-
这里在ideone上,同样的错误:ideone.com/0IV1Sc#view_edit_box
-
theThing = []创建一个空数组,因此索引 0 不存在。 -
我对 Python 比较陌生(来自 JavaScript 背景),所以我觉得这很令人惊讶。在 JavaScript 中,您可以简单地使用
var theThing = new Array(); theThing[0] = 0;将theThing的第 0 个元素设置为 0。 -
代替
theThing[0]=0,试试theThing.append(0)。 -
原来在Python中初始化一个特定大小的数组其实是可以的:stackoverflow.com/questions/6142689/…
标签: python