如何计算可迭代中的非null元素? [英] How to count non-null elements in an iterable?

查看:181
本文介绍了如何计算可迭代中的非null元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找以下代码段的更好/更多Pythonic解决方案

I'm looking for a better/more Pythonic solution for the following snippet

count = sum(1 for e in iterable if e)


推荐答案

len(filter(None, iterable))

使用作为过滤器的谓词,只是说要使用项目的真实性。 (可能更清楚的是 len(过滤器(bool,iterable))

Using None as the predicate for filter just says to use the truthiness of the items. (maybe clearer would be len(filter(bool, iterable)))

这篇关于如何计算可迭代中的非null元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆