Home > Back-end >  Remove Entries From Lists in Lists
Remove Entries From Lists in Lists

Time:07-29

I want to use one list to remove entries from another list, which in itself isn't hard with one level. But I'm having problems doing this with lists in lists (multiple levels)

list1 = [['orange', 'apple'], ['stone', 'wood', ['stone', 'stone', 'raven']]]

exclusionList = ["stone"]

The result I want:


>>> [['orange', 'apple'], ['wood', ['raven']]]

The solution should be able to dynamically adjust to the amount of list levels.

CodePudding user response:

A recursive approach:

list1 = [['orange', 'apple'], ['stone', 'wood', ['stone', 'stone', 'raven']]]

exclusionList = ["stone"]


def remove(lst, exclusion):
    result = []
    for e in lst:
        if isinstance(e, list):
            result.append(remove(e, exclusion))
        elif e not in exclusion:
            result.append(e)
    return result


res = remove(list1, exclusionList)
print(res)

Output

[['orange', 'apple'], ['wood', ['raven']]]

CodePudding user response:

This seems like it would admit a recursive solution. To begin with, here's what you probably have for normal, "one-level" (flat) lists.

#there's better ways to implement this function specifically
def remove_items(main_list, blacklist):
    for item in blacklist:
        if item in main_list:
            main_list.remove(item)

The solution is to apply this to your list, and each of its elements, recursively.

def remove_items_nested(main_list, blacklist):
    remove_items(main_list, blacklist)
    for sublist in main_list:
        if not isinstance(sublist, list): continue
        remove_items_nested(sublist, blacklist)
  • Related