[英]List index out of range when trying to remove instance from list
The out of range error shows when I try to remove an instance from a list but doesn't pop up when I just pass the statement?当我尝试从列表中删除一个实例但在我刚刚通过语句时没有弹出时,会显示超出范围的错误?
for x in range(len(urls)-1):
if urls[x] == None:
urls.remove(urls[x])
This is because you're removing from the list while starting the loop executing len(url) - 1
times.这是因为您在开始执行
len(url) - 1
次的循环时从列表中删除。 Total number of iterations will not be adjusted once you start removing from the list;一旦您开始从列表中删除,迭代总数将不会调整; and decreasing the length.
并减少长度。 Instead, you should use list comprehension for this.
相反,您应该为此使用列表推导。
new_list = [x for x in urls if x is not None]
This will happen even if there is a single None
in your list.即使您的列表中只有一个
None
也会发生这种情况。
The last index of the list which was valid before loop, will not be valid after popping a None
because the list has shrunk by one.在循环之前有效的列表的最后一个索引在弹出
None
后将无效,因为列表已经缩小了一个。
Subsequent popping of your None
element will result in subsequent shrinking of list and subsequent invalidity of 'second, third, fourth... from last' indexes.您的
None
元素的后续弹出将导致列表的后续缩小以及“第二个、第三个、第四个......从最后一个”索引的后续无效。
Check workarounds here How to remove items from a list while iterating?在此处检查解决方法如何在迭代时从列表中删除项目?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.