2017-04-04 33 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" 
相关问题