简体   繁体   English

尝试从列表中删除实例时列表索引超出范围

[英]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.

相关问题 尝试将列表中的数字添加到另一个列表时出现列表索引超出范围错误 - getting list index out of range error when trying to add a a number from a list into a another list 尝试从数字列表创建字典,但列表索引超出范围 - Trying to create a dictionary from a list of numbers, but list index is out of range 我试图基于另一个列表中的项目(在循环内)从列表中删除项目。 错误:列表索引超出范围 - I am trying to remove items from a list based upon items from another list (inside a loop). error: list index out of range 尝试从列表中删除项目时出现“ IndexError:列表分配索引超出范围” - “IndexError: list assignment index out of range” when trying to delete an item from a list 尝试删除list [i] [0]和list [i] [1] == 0的列表中的行时引发“超出范围” - “list out of range” thrown when trying to remove rows in list of list where list[i][0] and list[i][1] == 0 IndexError:尝试编程参数时列出索引超出范围 - IndexError: list index out of range when trying to program an argument IndexError:尝试运行cProflie时,列表索引超出范围 - IndexError: list index out of range when trying to run cProflie 尝试读取 Python 中的 txt 文件时,列表索引超出范围 - List index out of range when trying to read in a txt file in Python 尝试导入 csv 时列表索引超出范围 - List index out of range when trying to import csv 试图从 CSV 文件中读取数据,列表索引超出范围? - Trying to read in data from a CSV file, list index out of range?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM