Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
设置Python数组的索引_Python - Fatal编程技术网

设置Python数组的索引

设置Python数组的索引,python,Python,我试图在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 在Py

我试图在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中设置数组索引的正确语法是什么?

您试图分配给一个不存在的位置。如果要向列表中添加元素,请执行以下操作

theThing.append(0)
如果确实要分配给索引0,则必须首先确保列表非空

theThing = [None]
theThing[0] = 0

Python列表没有固定的大小。要设置第0个元素,您需要有第0个元素:

>>> theThing = []
>>> theThing.append(12)
>>> theThing
[12]
>>> theThing[0] = 0
>>> theThing
[0]
JavaScript的数组对象的工作方式与Python的稍有不同,因为它为您填充了以前的值:

> x
[]
> x[3] = 5
5
> x
[undefined × 3, 5]

这取决于你真正需要什么。首先你必须 在您的情况下,您可以使用smth,如:

lVals = [] 
lVals.append(0)
>>>[0]
lVals.append(1)
>>>[0, 1]
lVals[0] = 10
>>>[10, 1]

这是在ideone上,有相同的错误:theThing=[]创建了一个空数组,因此索引0不存在。我与来自JavaScript背景的Python比较不相似,因此我发现这令人惊讶。在JavaScript中,您只需执行var theThing=newarray;第[0]项=0;要将thing的第0个元素设置为0。而不是thing[0]=0,请尝试使用thing.append0。事实证明,在Python中可以使用特定大小初始化数组:thing.append12如何影响此处的数组?thing.append12在当前空数组的末尾添加一个12。@AndersonGreen:列表为空,所以没有第0个元素。我刚刚加了。附录12给列表一个。JavaScript的语法可能会让你感到困惑。是否可以初始化一个具有特定大小的空数组,例如长度为10的空数组?@AndersonGreen:不太可能。您可以使用dothing=[None for i in range10],但该列表仍将包含10个元素。