简体   繁体   English

如何从列表列表中删除多个元素?

[英]How to remove multiple elements from a list of lists?

I have list of list elements.我有列表元素的列表。 In my case, I am using dlib tracker.就我而言,我使用的是 dlib 跟踪器。 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.每当我在列表中找到 4 时,我都想删除列表项。

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:预期 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: 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 :此任务可以使用列表理解(如已显示)或使用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. 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. filter返回可迭代,所以我使用list来获取列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM