I have list of list elements. In my case, I am using dlib tracker. Appending all detected tracker to a list. I am trying to remove some of the tracker from the list. To make it simple, I have a list like below,
[[1, 2, 3], [4,5,6], [7, 8,9], [2,54,23], [4,12,5], [3,2,6]]
I want to remove list item whenever I found 4 in the list.
For that I used below snippet to find the index to remove elements.
t= [[1, 2, 3], [4,5,6], [7, 8,9], [2,54,23], [4,12,5], [3,2,6]]
del_item = []
idx = 0
for item in t:
if 4 in item:
del_item.append(idx)
idx+=1
print(del_item)
So far good. I have index of elements to be deleted. I am stuck at how to delete multiple indexes in list of list?
Expected output:
[[1, 2, 3], [7, 8,9], [2,54,23], [3,2,6]]
You can do it simply with one line using list comprehension:
trackers = [[1, 2, 3], [4,5,6], [7, 8,9], [2,54,23], [4,12,5], [3,2,6]]
filtered = [x for x in trackers if 4 not in x]
print(filtered)
Output:
[[1, 2, 3], [7, 8,9], [2,54,23], [3,2,6]]
This task might be done using list comprehension (as already shown) or using filter
:
t = [[1, 2, 3], [4,5,6], [7, 8,9], [2,54,23], [4,12,5], [3,2,6]]
tclean = list(filter(lambda x:4 not in x, t))
print(tclean) # [[1, 2, 3], [7, 8, 9], [2, 54, 23], [3, 2, 6]]
To use filter
you need function - in this case I used lambda to make nameless function, though normal function might be used too. filter
return iterable so I used list
on it to get list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.