【问题标题】:How to remove multiple elements from a list of lists?如何从列表列表中删除多个元素?
【发布时间】:2020-09-28 12:48:29
【问题描述】:

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

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

每当我在列表中找到 4 时,我都想删除列表项。

为此,我在 sn-p 下面使用了查找要删除元素的索引。

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)

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

预期输出:

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

【问题讨论】:

  • [sub_l for sub_l in t if 4 not in sub_l]
  • [i for i in t if 4 not in i]

标签: python python-3.x list dlib


【解决方案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]]

【讨论】:

    【解决方案2】:

    这个任务可以使用列表理解(如已经显示的)或使用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 return iterable 所以我使用list 来获取列表。

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多