在词典列表中搜索

2024-10-03 21:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单。如何计算带有'label':'car'的元素数

另外,如何创建一个包含所有元素的全新列表,这些元素都有“label”:“car”

result = [{'bottomright': {'x': 434, 'y': 102},
  'confidence': 0.3357535,
  'label': 'car',
  'topleft': {'x': 418, 'y': 88}},
 {'bottomright': {'x': 621, 'y': 120},
  'confidence': 0.55622935,
  'label': 'cup',
  'topleft': {'x': 580, 'y': 106}},
 {'bottomright': {'x': 136, 'y': 201},
  'confidence': 0.32227623,
  'label': 'truck',
  'topleft': {'x': 77, 'y': 166}},
 {'bottomright': {'x': 229, 'y': 235},
  'confidence': 0.3240861,
  'label': 'car',
  'topleft': {'x': 184, 'y': 198}},
 {'bottomright': {'x': 281, 'y': 265},
  'confidence': 0.63466769,
  'label': 'person',
  'topleft': {'x': 226, 'y': 220}},
 {'bottomright': {'x': 204, 'y': 286},
  'confidence': 0.54358166,
  'label': 'car',
  'topleft': {'x': 141, 'y': 233}},
 {'bottomright': {'x': 251, 'y': 331},
  'confidence': 0.70285547,
  'label': 'car',
  'topleft': {'x': 182, 'y': 253}},
 {'bottomright': {'x': 432, 'y': 361},
  'confidence': 0.74345809,
  'label': 'surfboard',
  'topleft': {'x': 370, 'y': 277}}]

Tags: 元素列表字典resultcarlabelpersoncup
2条回答

请尝试以下代码:

include_label_list = [i for i in result if i.get('label') == 'car']
counter = len(include_label_list)

你有一个新的列表,只有标签与汽车,你的计数器应该是这个新的名单长度

尝试过滤功能:

len(list(filter(lambda dic: dic['label'] == 'car', result)))

要创建一个全新的列表,请执行以下操作:

list(filter(lambda dic: dic['label'] == 'car', result))

记住在前面强制转换一个list转换器,因为filter会返回一个“filter object”本身

相关问题 更多 >