[英]How to remove multiple elements from a list of lists?
我有列表元素的列表。 就我而言,我使用的是 dlib 跟蹤器。 將所有檢測到的跟蹤器附加到列表中。 我正在嘗試從列表中刪除一些跟蹤器。 為了簡單起見,我有一個如下列表,
[[1, 2, 3], [4,5,6], [7, 8,9], [2,54,23], [4,12,5], [3,2,6]]
每當我在列表中找到 4 時,我都想刪除列表項。
為此,我使用下面的代碼片段來查找要刪除元素的索引。
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)
到目前為止很好。 我有要刪除的元素的索引。 我被困在如何刪除列表列表中的多個索引?
預期 output:
[[1, 2, 3], [7, 8,9], [2,54,23], [3,2,6]]
您可以使用列表推導簡單地用一行來完成:
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]]
此任務可以使用列表理解(如已顯示)或使用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
返回可迭代,所以我使用list
來獲取列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.