简体   繁体   English

枚举“列表索引超出范围”的问题

[英]Enumerate problem with "list index out of range"

I have a chunk of code that basically goes like this:我有一段代码基本上是这样的:

x = [6237,5342,9991,6237,1021]
y = [0,0,0,0,0]
for i in x:
  index = x.index(i)
  actualindex = [i for i, n in enumerate(x) if n == i][y[index]]

apparently there is an error on the fifth line where "list index out of range" the first time that i = 6237 .显然在第五行出现错误,其中第一次i = 6237时“列表索引超出范围”。

I changed n == i into n == 6237 and everything worked, but when I changed it back to n == i it stopped working again and returned the same error as before.我将n == i更改为n == 6237并且一切正常,但是当我将其更改回n == i时它再次停止工作并返回与以前相同的错误。

You are trying to access an element from an empty list.您正在尝试访问空列表中的元素。

This code:这段代码:

x = [6237,5342,9991,6237,1021]
my_list = [i for i, n in enumerate(x) if n == i]

always returns an empty list, since the number of elements in x is only 5 i can only ever be equal to {0,1,2,3,4} therefore i can never equal any of the elements in x since all of them are greater than 4.总是返回一个空列表,因为 x 中的元素数量只有 5只能等于 {0,1,2,3,4} 因此永远不能等于 x 中的任何元素,因为它们都是大于 4。

print(len(my_list)) # 0
my_list[0]

gives "list index out of range" because any index you give to the list will be out of range since its length is zero (its an empty list).给出“列表索引超出范围”,因为您给列表的任何索引都将超出范围,因为它的长度为零(它是一个空列表)。

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

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