Remove items from list: pythonic way

I have a list of lists (only two nested levels):

my_list = [['A'], ['B'], ['C','D','A','B'], ['E'], ['B', 'F', 'G'], ['H']]

I have a list of items to delete in my_list:

to_del = ['A','B']

this is my code idea for removing elements to_delfrom my_list:

for i in my_list:
    for d in to_del:
        if d in i:
            i.remove(d)

Conclusion: [[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]

Here are my questions:

  • Can you suggest a more pythonic / elegant way to do the same
  • Can you suggest a reasonable way to summarize the number of nested levels for example my_list = [ ['A'], ['B'], ['C', ['D', 'E', ['F']], 'G'], ['H'] ]
  • An ideal method would have a logical argument empty_liststo decide whether to keep empty lists.
+3
source share
2 answers

Given the nested lists:

[[y for y in x if y not in to_del] for x in my_list]

With list and lambda filter:

[filter(lambda y: y not in to_del, x) for x in my_list]

Trying the general case of randomly nested lists:

def f(e):
    if not isinstance(e,list):
        if e not in to_del:
            return e
    else:
        return filter(None,[f(y) for y in e])

to_del = ['A','B']
my_list= [['A'], ['B',['A','Z', ['C','Z','A']]], ['C','D','A','B'],['E'], ['B','F','G'], ['H']]

>>> f(my_list)
[[['Z', ['C', 'Z']]], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
+3

:

my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]

:

>>> my_list
[[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
+6

Source: https://habr.com/ru/post/1664778/


All Articles