2010-04-09 50 views
1
pt=[2] 
pt[0]=raw_input() 

當我這樣做,並給一個輸入假設1011,它說列表索引錯誤 - 「列表分配索引超出範圍」。我可以知道爲什麼嗎?我認爲我無法正確地分配清單。那麼如何在python中分配2個元素的數組呢?在Python中分配一個列表

+2

此代碼應該可以工作,問題可能在其他地方...... – ChristopheD 2010-04-09 09:35:01

+1

您能否發佈一個完整的示例來演示可重現的問題? – 2010-04-09 09:40:21

回答

4

試試這個:

pt = list() 
pt.append(raw_input()) 
pt.append(raw_input()) 
print pt 

現在您的列表中有兩個元素。一旦你更熟悉Python語法,你還不如寫:

pt = [raw_input(), raw_input()] 

另外請注意,列表是不與Java或C數組混淆:列出動態增長。在創建新列表時,您不必聲明大小。

順便說一句:我在交互式shell中試用了你的例子。它的工作原理,但可能並不如你預期:

>>> pt = [2] 
>>> pt[0] = raw_input() 
1011 
>>> pt 
['1011'] 

我猜你以爲pt = [2]將創建長度爲2的列表,所以像你提到一個pt[1] = raw_input()會失敗:

>>> pt = [2] 
>>> pt[0] = raw_input() 
1011 
>>> pt[1] = raw_input() # this is an assignment to an index not yet created. 
1012 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list assignment index out of range 

其實, pt = [2]創建一個列表與一個元件,在索引0具有值2

>>> pt = [2] 
>>> pt 
[2] 
>>> 

所以您可以如上所示分配給索引0,但分配給索引1不起作用 - 使用append追加到列表。

3

目前還不清楚你想要做什麼。我的猜測是,你正在試圖做到這一點:

pt = [2] # Create array with two elements? 
for i in range(2): 
    pt[i] = raw_input() 

注意,第一行不以兩個元素創建一個數組,它創建一個列表與一個元素:數字2。你可以代替試試這個,雖然有更Python的方式來做到這一點:

pt = [None] * 2 
for i in range(2): 
    pt[i] = raw_input()