在 Python 中做 countif 的好方法是什么 [英] What is a good way to do countif in Python

查看:43
本文介绍了在 Python 中做 countif 的好方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一个可迭代对象有多少个成员满足给定条件.我想以一种清晰、简单且最好是合理优化的方式来做.

I want to count how many members of an iterable meet a given condition. I'd like to do it in a way that is clear and simple and preferably reasonably optimal.

我目前最好的想法是:

sum(meets_condition(x) for x in my_list)

len([x for x in my_list if meets_condition(x)])

第一个基于迭代器的对于大列表来说可能更快.它与您用于测试任何和所有内容的形式相同.然而这取决于 int(True) == 1 这个事实,这有点难看.

The first one being iterator based is presumably faster for big lists. And it's the same form as you'd use for testing any and all. However it depends on the fact that int(True) == 1, which is somewhat ugly.

第二个对我来说似乎更容易阅读,但它与 any 和 all 形式不同.

The second one seems easier to read to me, but it is different from the any and all forms.

大家有更好的建议吗?是否有我遗漏的库函数?

Does anyone have any better suggestions? is there a library function somewhere that I am missing?

推荐答案

基于迭代器的方法很好.有一些细微的修改可以强调您正在计算的事实:

The iterator based approach is just fine. There are some slight modifications that can emphasize the fact that you are counting:

sum(1 if meets_condition(x) else 0 for x in my_list)
# or 
sum(1 for x in my_list if meets_condition(x))

和往常一样,如果意图从代码中看不出来,请将其封装在描述性命名的函数中:

And as always, if the intent isn't apparent from the code, encapsulate it in descriptively named function:

def count_matching(condition, seq):
    """Returns the amount of items in seq that return true from condition"""
    return sum(1 for item in seq if condition(item))

count_matching(meets_condition, my_list)

这篇关于在 Python 中做 countif 的好方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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