Home > Enterprise >  removing a sublist if a string in the sublist contains a substring (all values within all sublists a
removing a sublist if a string in the sublist contains a substring (all values within all sublists a

Time:11-23

Given nested list: mistake_list = [['as','as*s','sd','*ssa'],['a','ds','dfg','mal']]

Required output: corrected_list = [['a','ds','dfg','mal']]

Now the given list can contain hundreds or thousands of sublists in which the strings may or may not contain the special character *, but if it does that whole sublist has to be removed.

I have shown an example above where the mistake_list is the input nested list, and corrected_list is the output nested list.

NOTE: all sublists have an equal number of elements (I don't think it is necessary to know this though)

CodePudding user response:

You can use list comprehension:

mistake_list = [['as','as*s','sd','*ssa'],['a','ds','dfg','mal']]

corrected_list = [sublst for sublst in mistake_list if not any('*' in s for s in sublst)]
print(corrected_list) # [['a', 'ds', 'dfg', 'mal']]

The filtering condition here checks whether there is any '*' character in each item of sublst.

CodePudding user response:

The filter function can help you:

mistake_list = [['as','as*s','sd','*ssa'],['a','ds','dfg','mal']]
corrected_list = list(filter(lambda l: not any("*" in x for x in l), mistake_list))

print(corrected_list)
[['a', 'ds', 'dfg', 'mal']]
  • Related