列出Python中的索引错误

问题描述 投票:-2回答:2

在这个程序中,我想从列表中搜索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);
python search
2个回答
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
投票

你的病情应该是:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.