Python从列表提取指定标签元素失败,始终得到空列表求助
问题排查与解决
核心问题分析
你的代码存在三个关键错误:
- 条件判断逻辑错误:
if 'tags' == 'lipstick'是直接比较两个固定字符串,永远为False,根本不会触发添加操作。你需要检查的是每个区域对象的tags列表中是否包含lipstick标签。 - 循环层级错误:你的
values_list是嵌套结构,外层列表的第二个元素才是包含annotated_regions的字典,直接遍历外层列表无法访问到具体的标签数据。 - 未正确遍历嵌套的区域数据:标签存储在
annotated_regions列表的每个子字典中,需要深入到这一层级才能读取标签。
修正后的代码
假设你的values_list完整结构如下(补全你提供的不完整代码):
values_list = [ ['lipstick', 'spray', 'polish', 'other'], [ { 'annotated_regions': [ {'tags': ['lipstick'], 'region_type': 'Box', 'region': {'xmin': 0.6413427734375, 'ymin': 0.2342342380079588, 'xmax': 0.234234230703125, 'ymax': 0.4645647705992509}}, {'tags': ['polish'], 'region_type': 'Box', 'region': {'xmin': 0.234234334375, 'ymin': 0.234234224531835, 'xmax': 0.4564560546875, 'ymax': 0.2342341481741573}}, {'tags': ['lipstick'], 'region_type': 'Box', 'region': {'xmin': 0.123, 'ymin': 0.456, 'xmax': 0.789, 'ymax': 0.901}} ] } ] ]
提取所有带lipstick标签的区域对象,代码如下:
lipstick_tag = [] # 定位到包含annotated_regions的字典 annotated_group = values_list[1][0] # 遍历每个标注区域 for region in annotated_group['annotated_regions']: # 检查当前区域的标签列表是否包含目标值 if 'lipstick' in region['tags']: lipstick_tag.append(region) print(lipstick_tag)
代码说明
- 先通过
values_list[1][0]定位到存储标注区域的核心字典。 - 遍历
annotated_regions中的每个区域对象,判断其tags列表是否包含lipstick。 - 将符合条件的区域对象添加到目标列表
lipstick_tag中。
内容的提问来源于stack exchange,提问作者Helene
相关产品推荐
相关产品推荐

