简体   繁体   English

Python 中的列表索引错误

[英]List Index Error in Python

In this program, I want to search for a Number from a list.在这个程序中,我想从列表中搜索一个Number When I search a number that is in the list, it works correctly.当我搜索列表中的数字时,它可以正常工作。

But if I search a number that it is not in list, it gives me this Error:但是如果我搜索一个不在列表中的数字,它会给我这个错误:

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);

That's because i goes from 0 to len(liste) and inside the while loop you are increasing the i by one.那是因为 i 从 0 到 len(liste) 并且在 while 循环中您将 i 增加一。 So when it doesn't find the desired number and i gets the value i = len(liste), you increae it by 1 in the loop so you get the error because it exceeds the range of the list.因此,当它找不到所需的数字并且 i 获得值 i = len(liste) 时,您在循环中将其增加 1,因此您会收到错误,因为它超出了列表的范围。

you can use the following你可以使用以下

while (i<len(liste)):

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

Your condition should be:你的情况应该是:

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

This is because Python list indexing begins at 0.这是因为 Python 列表索引从 0 开始。

Therefore, for a list of length n you need to index from 0 to n-1 .因此,对于长度为n的列表,您需要索引从 0 到n-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM