列出Python中的索引错误

时间:2018-03-03 18:56:41

标签: python search

在这个程序中,我想从列表中搜索Number。当我搜索列表中的数字时,它可以正常工作。

但是,如果我搜索一个不在列表中的数字,它会给我这个错误:

Traceback (most recent call last): File "fourth.py", line 12, in <module> if(AranaElemean==liste[i]): IndexError: list index out of range

liste=[12,23,3489,15,345,23,9,234,84];

Number=11;
i=0;
Index=0;
isWhileActive=0;
while (i<len(liste) and Number!=liste[i]):
   i=i+1;

   if(Number==liste[i]):
      Index=i;
      isWhileActive=1;
   else:
      Index=0;


if(isWhileActive==0 and i!=0):
   print("Please Enter Valid Number.");
else:
   print("Index:",Index);

2 个答案:

答案 0 :(得分:2)

那是因为我从0到len(liste)并且在while循环中你将i增加一个。因此,当它找不到所需的数字并且我得到值i = len(liste)时,你在循环中将它增加1,这样你就会得到错误,因为它超出了列表的范围。

您可以使用以下

while (i<len(liste)):

   if(Number==liste[i]):
      Index=i;
      isWhileActive=1;
      break
   else:
      Index=0;
   i += 1

答案 1 :(得分:1)

你的病情应该是:

while (i<len(liste)-1 and Number!=liste[i])

这是因为Python列表索引从0开始。

因此,对于长度 n 的列表,您需要从0到 n-1 进行索引。