2017-04-04 87 views
2

我正在一個錯誤列表分配索引超出範圍下面的代碼:獲得一個錯誤:列表分配索引超出範圍

n=input("How many numbers?\n") 
print "Enter ",n," numbers..." 
a=[] 
for i in range(0,n): 
    a[i]=input() 

elem=input("Enter the element to be searched: ") 

for i in range(0,n): 
    if a[i]==elem: 
     flag=1 
     break 

if flag==1: 
    print "Item is present in the list" 
else: 
    print "Item is not present in the list" 
+1

使用'a.append()','不是A [1] ='。 – zondo

+3

請發佈堆棧跟蹤。 Python很好,可以告訴你有關錯誤的詳細信息...付出代價! – tdelaney

回答

1

添加某種類型的安全性INT,採用列表法追加和運營商

n = input("How many numbers?\n") 
n = int(n) 
print "Enter ", n, " numbers..." 
a = [] 
for i in range(n): 
    x = input() 
    a.append(x) 

elem = input("Enter the element to be searched: ") 

if elem in a: 
    print "Item is present in the list" 
else: 
    print "Item is not present in the list" 
+0

非常感謝。我的問題已解決。 –

0

你設置列表索引沒有它宣稱。見:

a=[] 

然後,你想要訪問一些索引?你正在閱讀一個字符串與輸入,在使用前轉換它。事情會是這樣的:

n = int(n) 
a= []*n 
0

使用它像這樣,

n=input("How many numbers?\n") 
print "Enter ",n," numbers..." 
# assigning with n times zero values which will get overwritten when you input values. 
a=[0]*n 
for i in range(0,n): 
    a[i]=input() 

elem=input("Enter the element to be searched: ") 

for i in range(0,n): 
    if a[i]==elem: 
     flag=1 
     break 

if flag==1: 
    print "Item is present in the list" 
else: 
    print "Item is not present in the list" 
相關問題