Home > Back-end >  Python - How to remove an element from a list in a list of lists of lists?
Python - How to remove an element from a list in a list of lists of lists?

Time:03-23

I would to remove an element from a list in a list of lists of lists? For example, if I have

[[[a,b,c],[b,c]],[[g,a,b,],[e,f]],[[q,e,d],[d,a]]]

I would like to be able to go through and remove a, which would yield

[[[b,c],[b,c]],[[g,b,],[e,f]],[[q,e,d],[d]]]

I initially tried to solve this by means of accessing the items by means of indexing and a series of for and if statements to remove them, but I was unable to get that working. Even if I was able to, I felt like that was probably a much more efficient way of accomplishing this task

I found this article that accomplishes a two-deep version (list of lists) of this issue, as opposed to a three-deep problem (list of lists of lists), by means of the following:

res = [[ele for ele in sub if ele != N] for sub in test_list]

However, I am unsure how to expand this to the three deep problem cases?

CodePudding user response:

Here is one way to do so if the list is always 3-depth.

data = [[["a", "b", "c"], ["b", "c"]], [["g", "a", "b", ], ["e", "f"]], [["q", "e", "d"], ["d", "a"]]]

res = [[[ele for ele in sub2 if ele != "a"] for sub2 in sub] for sub in data]
print(res)
# [[['b', 'c'], ['b', 'c']], [['g', 'b'], ['e', 'f']], [['q', 'e', 'd'], ['d']]]

CodePudding user response:

Here's a recursive function below that does what you wan't explained with code comments


lst = [[["a","b","c"],["b","c"]],[["g","a","b"],["e","f"]],[["q","e","d"],["d","a"]]]



def removeValueFromNestedList(lst,value):
    # If the type is not a list 
    # base case is reached
    if type(lst) is not list:
        return
    # If list contains value
    # remove it
    if value in lst:
        lst.remove(value)
    # Recursively call all the elements
    # in the list
    for elem in lst:
        removeValueFromNestedList(elem,value)
        


removeValueFromNestedList(lst,"a")
print(lst) # output: [[['b', 'c'], ['b', 'c']], [['g', 'b'], ['e', 'f']], [['q', 'e', 'd'], ['d']]]


  • Related