Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

What is a good way to do countif in Python

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.

My current best ideas are:

sum(meets_condition(x) for x in my_list)

and

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...