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

时间:2020-06-09 10:56:32

标签: python python-3.x list dlib

我有列表元素的列表。就我而言,我正在使用dlib跟踪器。将所有检测到的跟踪器添加到列表。我正在尝试从列表中删除一些跟踪器。为简单起见,我有一个如下列表,

['POINT (3 0)', 'POINT (2 0)', 'POINT (1 0)', 'POINT (1 1)', 'POINT (3 1)',
 'POINT (2 1)', 'POINT (2 2)', 'POINT (3 2)', 'POINT (1 2)', 'POINT (2 3)',
 'POINT (3 3)', 'POINT (1 3)', 'POINT (2 4)', 'POINT (1 4)', 'POINT (3 4)']

我想在列表中找到4时删除列表项。

为此,我在下面的代码段中找到了删除元素的索引。

[[1, 2, 3], [4,5,6], [7, 8,9], [2,54,23], [4,12,5], [3,2,6]]

到目前为止很好。我有要删除的元素的索引。我被困在如何删除列表列表中的多个索引?

预期输出:

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)

2 个答案:

答案 0 :(得分:1)

您可以使用列表理解功能只用一行就可以做到:

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)

输出:

[[1, 2, 3], [7, 8,9], [2,54,23], [3,2,6]]

答案 1 :(得分:1)

可以使用列表理解(如已显示)或使用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]]

要使用filter,您需要功能-在这种情况下,我可以使用lambda来实现无名功能,尽管也可以使用普通功能。 filter返回可迭代,因此我在其上使用了list来获取列表。

相关问题