简体   繁体   English

遍历嵌套列表并删除某个元素

[英]Loop through nested lists and remove a certain element

All I want to do is loop through a nested list (eg [[2],1,[4,[]]] ) and remove an element if it fits the condition I set it for it.我想要做的就是遍历一个嵌套列表(例如[[2],1,[4,[]]] )并删除一个元素,如果它符合我为它设置的条件。

eg:例如:

  • if the element is an int -> remove如果元素是 int -> 删除
  • if the element is any empty list -> remove如果元素是任何空列表 -> 删除

I would appreciate any help I get with examples provided so i can understand.我将不胜感激提供的示例提供的任何帮助,以便我理解。 Would prefer not to use libraries.宁愿不使用库。

Thank you so much for reading this far!非常感谢你读到这里!

Question has been edited as the code gives different errors with different inputs.问题已被编辑,因为代码给出了不同输入的不同错误。

For reference here is the code I used but I'm getting different error now so it might not be relevant:这里的参考是我使用的代码,但我现在得到不同的错误,所以它可能不相关:

for i in range(len(l)): for j in range(len(l)): if l[i][j] == []: l.remove(l[i][j])

Here is how we manages a similar issue we had an ArrayList of correct spelled words this is the ArrayList capture and we wanted to compare this list to a String[] strArray that had all the words correct spelling and misspelled words.以下是我们处理类似问题的方法,我们有一个拼写正确的单词 ArrayList 这是 ArrayList 捕获,我们想将此列表与所有单词拼写正确和拼写错误的 String[] strArray 进行比较。 So we removed all the correct spelled words and put the misspelled word in the ArrayList list then just added these back to the String[] strArray所以我们删除了所有拼写正确的单词并将拼写错误的单词放在 ArrayList 列表中,然后将它们添加回 String[] strArray
I would like to take credit for this code but it belongs to a fellow named Chris Jester-Young here is a link to his SO Post look at the code under Edit3我想感谢这段代码,但它属于一个名叫 Chris Jester-Young 的人,这里是他的 SO Post 的链接,请查看 Edit3 下的代码
Edit3 编辑3

Here is our implementation of the code这是我们的代码实现

    for(int P = 0; P < capture.size();P++){

    String gotIT = capture.get(P);     
    String[] EMPTY_STRING_ARRAY = new String[0];
    List<String> list = new ArrayList<>();
    Collections.addAll(list, strArray);
    list.removeAll(Arrays.asList(gotIT));
    strArray = list.toArray(EMPTY_STRING_ARRAY); 
    // Code above removes the correct spelled words from ArrayList capture
    // Leaving the misspelled words in strArray then below they are added 
    // to the cboMisspelledWord which then holds all the misspelled words
}

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

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