【问题标题】:get count of values associated with key in dict python获取与dict python中的键关联的值的计数
【发布时间】:2016-02-08 12:10:46
【问题描述】:

dict 的列表是这样的。

[{'id': 19, 'success': True, 'title': u'apple'},
 {'id': 19, 'success': False, 'title': u'some other '},
 {'id': 19, 'success': False, 'title': u'dont know'}]

我想计算有多少字典有successTrue

我试过了,

len(filter(lambda x: x, [i['success'] for i in s]))

如何使用 pythonic 方式使它更优雅?

【问题讨论】:

    标签: python python-2.7 dictionary


    【解决方案1】:

    您可以使用sum() 将您的布尔值相加; True 在数字上下文中为 1,False 为 0:

    sum(d['success'] for d in s)
    

    这是可行的,因为 Python bool 类型是 int 的子类,出于历史原因。

    如果你想明确表达,你可以使用条件表达式,但在我看来,可读性并没有提高:

    sum(1 if d['success'] else 0 for d in s)
    

    【讨论】:

      【解决方案2】:

      另一种方法是

      len(filter(lambda x:x['success'], s))
      

      如果您在 dict 中没有“成功”,它可能会崩溃

      len(filter(lambda x:x.get('success',False), s))
      

      可以完成这项工作

      【讨论】:

        【解决方案3】:

        这是你如何优雅地做到这一点:

        args = [
            {'id': 19, 'success': True, 'title': u'apple'},
            {'id': 19, 'success': False, 'title': u'some other '},
            {'id': 19, 'success': False, 'title': u'dont know'}
        ]
        
        
        count_success = lambda x: 1 if x['success'] else 0
        
        success_list = map(count_success, args)
        
        print(sum(success_list))  # Python 3
        print sum(success_list)   # Python 2
        

        显示:

        1
        

        这就像它得到的 Pythonic。

        【讨论】:

          猜你喜欢
          • 2019-01-08
          • 1970-01-01
          • 1970-01-01
          • 2020-07-22
          • 1970-01-01
          • 2021-02-26
          • 1970-01-01
          • 2022-01-11
          • 1970-01-01
          相关资源
          最近更新 更多