【问题标题】:Searching in List of Dictionary在字典列表中搜索
【发布时间】:2018-02-28 01:34:03
【问题描述】:

我有一个字典列表。如何计算带有 '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}}]

【问题讨论】:

    标签: python list dictionary search


    【解决方案1】:

    试试过滤功能:

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

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

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

    记得在前面加上list 转换器,因为filter 本身会返回一个“过滤器对象”。

    【讨论】:

      【解决方案2】:

      试试下面的代码:

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

      你得到了一个只有汽车标签的新列表,你的这个列表的计数器应该是这个新列表的长度!

      【讨论】:

        猜你喜欢
        • 2022-11-12
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        相关资源
        最近更新 更多