如果在另一个嵌套列表中找不到嵌套列表项,该如何删除?

问题描述 投票:0回答:1

我有两个嵌套的不同结构的列表:

image_annotations=[['img---615.png', [[241, 429, 265, 459], [331, 340, 358, 382], [327, 293, 343, 318]]], ['img---16050.png', [[159, 74, 190, 108], [29, 57, 56, 93], [285, 310, 319, 344], [129, 247, 156, 288], [213, 285, 244, 324], [330, 151, 364, 174], [0, 373, 18, 416]]], ['img---11631.png', [[356, 25, 384, 63], [150, 29, 176, 68], [423, 50, 450, 87], [440, 466, 470, 499], [36, 41, 73, 80]]]]
keep=[[241, 429, 265, 459], [331, 340, 358, 382], [159, 74, 190, 108], [29, 57, 56, 93], [356, 25, 384, 63]]

我想遍历较大的列表image_annotations,并删除在较小的列表keep中找不到的所有嵌套列表。我需要较大列表的结构保持不变(每个图像仅一个列表),但是每个图像列表中的元素数量可以变化。我已经尝试过类似的方法:

keep = []
for annotation in image_annotations:
    for j in annotation[1]:
        for i in pick_list:
            if i[0] == j[0] and i[1] == j[1] and i[2] == j[2] and i[3] == j[3]:
                keep.append(annotation)

但是这只会返回相同嵌套图像列表的多个副本,例如keep=[['img---615.png', [[241, 429, 265, 459], [331, 340, 358, 382], [327, 293, 343, 318]]], ['img---615.png', [[241, 429, 265, 459], [331, 340, 358, 382], [327, 293, 343, 318]]]]

我的预期输出是这样的:image_annotations=[['img---615.png', [[241, 429, 265, 459], [331, 340, 358, 382]]], ['img---16050.png', [[159, 74, 190, 108], [29, 57, 56, 93]]], ['img---11631.png', [[356, 25, 384, 63]]]]

[理想情况下,我只想直接从列表中删除image_annotations中找不到的元素,而不是像上面那样新建一个列表。我一直在阅读综合列表可能是最好的选择,但是我不确定如何为更复杂的嵌套列表结构实现某些东西。

python list nested list-comprehension
1个回答
0
投票

如果将keep列表更改为一组元组,则可以使用带有列表理解功能的for循环遍历注释,以检查每个注释列表是否在保留集中:

keep

输出:

image_annotations=[['img---615.png', [[241, 429, 265, 459], [331, 340, 358, 382], [327, 293, 343, 318]]], ['img---16050.png', [[159, 74, 190, 108], [29, 57, 56, 93], [285, 310, 319, 344], [129, 247, 156, 288], [213, 285, 244, 324], [330, 151, 364, 174], [0, 373, 18, 416]]], ['img---11631.png', [[356, 25, 384, 63], [150, 29, 176, 68], [423, 50, 450, 87], [440, 466, 470, 499], [36, 41, 73, 80]]]]

keep=[[241, 429, 265, 459], [331, 340, 358, 382], [159, 74, 190, 108], [29, 57, 56, 93], [356, 25, 384, 63]]
keepset = {tuple(l) for l in keep}

for annotation in image_annotations:
    annotation[1] = [l for l in annotation[1] if tuple(l) in keepset]

print(image_annotations)
© www.soinside.com 2019 - 2024. All rights reserved.