我有两个嵌套的不同结构的列表:
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
中找不到的元素,而不是像上面那样新建一个列表。我一直在阅读综合列表可能是最好的选择,但是我不确定如何为更复杂的嵌套列表结构实现某些东西。
如果将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)