2013-04-05 93 views
0

我正在嘗試設置了一個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 

什麼是在Python中設置數組索引的正確語法?

+0

這是ideone,用同樣的錯誤:http://ideone.com/0IV1Sc#view_edit_box – 2013-04-05 02:00:18

+0

'theThing = []'創建一個空數組,所以索引0不存在。 – 2013-04-05 02:01:47

+1

我與Python相比並不相似(來自JavaScript背景),所以我覺得這很令人驚訝。在JavaScript中,您可以簡單地執行'var theThing = new Array(); theThing [0] = 0;'將theThing'的第0個元素設置爲0. – 2013-04-05 02:01:54

回答

5

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] 
+0

'theThing.append(12)'在這裏如何影響數組? – 2013-04-05 02:05:41

+0

'theThing.append(12)'在(當前爲空)數組的末尾添加一個12。 – 2013-04-05 02:06:42

+0

@AndersonGreen:列表是空的,所以沒有第0個元素。我剛剛添加了'.append(12)'給出一個列表。 JavaScript的語法可能會讓你失望。 – Blender 2013-04-05 02:08:21

1

你試圖分配到一個不存在的位置。如果你想一個元素添加到列表中,這樣做

theThing.append(0) 

如果你真的想分配給索引0,那麼你必須保證該列表非空第一。

theThing = [None] 
theThing[0] = 0 
1

這取決於你真正需要什麼。首先,你必須read python tutorials about list. 在你情況下,你可以使用像水木清華:

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