I have a 2D list having the numbers 1 to n, each of them appearing twice. I would like to find the fastest way to get rid of m of them completely. Example:
input = [[], [6,7,7,6], [1,2,3,2,3,1], [], [4,4,5,5]]
#remove 4 and 1
output = [[], [6,7,7,6], [2,3,2,3], [], [5,5]]
(lists can be empty)
I came up with that code but I do have the feeling this is somehow slow since its creating a new list. Is there a smarter way to do so?
input = [[], [6,7,7,6], [1,2,3,2,3,1], [], [4,4,5,5]]
output = list()
to_remove = [1,4]
for inner in input:
new_inner = [x for x in inner if x not in to_remove]
output.append(new_inner)
CodePudding user response:
You can do it with two list comprehensions, plus using a set which has quicker lookups for large number of elements to remove:
input = [[], [6,7,7,6], [1,2,3,2,3,1], [], [4,4,5,5]]
to_remove = set([1,4])
output = [[x for x in inner if x not in to_remove] for inner in input]