简体   繁体   English

迭代时减少列表索引超出范围错误列表

[英]List index out of range error list reduced while iteration

I think I'm getting an error because the range of the list is reduced during iteration of the loop. 我认为我遇到了错误,因为在循环的迭代过程中列表的范围减小了。 I have 95 nested lists within a large list mega4 , and I'm trying to delete some strings with if and else. 我在mega4大型列表中有95个嵌套列表,并且我尝试使用if和else删除一些字符串。 The list ufields consist of 18 strings. 列表ufields由18个字符串组成。

>>> for i in range(len(mega4)):
...     for j in range(len(mega4[i])):
...         for f in ufields:
...             if (f in mega4[i][j]) is False:
...                 mega4[i].remove(mega4[i][j])
...             else:
...                 pass
... 
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
IndexError: list index out of range

The fourth line is basically asking if each element within mega4[i] has each strings within ufields , how can I remove the mega4[i][j] in this case? 第四行基本上询问是否内的每个元件mega4[i]具有内的每个字符串ufields ,我怎样才能去除mega4[i][j]在这种情况下?

Edit: 编辑:

I followed comments below and tried building a new list but this one does not seem to work 我遵循以下评论并尝试建立新列表,但该列表似乎不起作用

>>> mega5 = []
>>> for i in range(len(mega4)):
...     for f in ufields:
...         mega5.append([x for x in mega4[i] if f in x is True])

len(mega5) is larger than len(mega4) whereas it should be the same. len(mega5)大于len(mega4) ,但应该相同。

  1. Depending on how ufields is defined, you could eliminate the innermost loop by using if mega4[i][j] in ufields . 根据ufields的定义方式,可以通过if mega4[i][j] in ufields使用if mega4[i][j] in ufields消除最里面的循环。

  2. Instead of modifying mega4 within this loop, you could build up a list of what elements you want to eliminate, and then do the actual elimination afterwards (looping over your list of candidates instead of mega4 itself). 除了mega4在此循环中修改mega4 ,您可以构建消除哪些元素的列表,然后再进行实际消除(遍历候选列表而不是mega4本身)。

Simpler way: 更简单的方法:

result = [[sub for sub in item if sub] for item in mega4]

Your way wasn't working because you were editing list while iterating over it. 您的方式无效,因为您在迭代列表时正在编辑列表。

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

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