Delete Items From List Of List: Pythonic Way
I've this kind of list of list (only two nested level): my_list = [['A'], ['B'], ['C','D','A','B'], ['E'], ['B', 'F', 'G'], ['H']] I've a list of items to delete in my_list: to_del
Solution 1:
Try list comprehension:
my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
Output:
>>> my_list
[[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
Solution 2:
With nested list comprehensions:
[[y foryin x if y not in to_del] forxin my_list]
With list comprehension and lambda filter:
[filter(lambda y: y notin to_del, x) for x in my_list]
An attempt for the general case of arbitrarily nested lists:
deff(e):
ifnotisinstance(e,list):
if e notin to_del:
return e
else:
returnfilter(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']]
Post a Comment for "Delete Items From List Of List: Pythonic Way"