字典列表就像 .
[{'id': 19, 'success': True, 'title': u'apple'},
{'id': 19, 'success': False, 'title': u'some other '},
{'id': 19, 'success': False, 'title': u'dont know'}]
我想计算有多少 dict success
为 True
。
我试过了,
len(filter(lambda x: x, [i['success'] for i in s]))
如何使用 pythonic 方式使其更优雅?
最佳答案
您可以使用sum()
来添加您的 bool 值; 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)
关于python - 获取与 dict python 中的键关联的值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35269374/