Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: filter() an iterable, count filtered and not filtered items

I have a big Iterable.
and i want to filter it using filter() function.
how can i count (in some elegant way) how many items are filtered?
(same question could be for map(), reduce() etc)

sure i can just make:

items = get_big_iterable()
count_good = 0
count_all = 0
for item in items:
    if should_keep(item):
        count_good += 1
    count_all += 1

print('keep: {} of {}'.format(count_good, count_all))

is it somehow possible with filter()?

items = filter(should_keep, get_big_iterable()) 
for item in items:
    #... using values here ..
    #possible count not filtered items here too? 

I should not iterate twice, and would like to use filter() or similar solution

like image 683
ya_dimon Avatar asked Feb 06 '26 20:02

ya_dimon


1 Answers

Another option is to use the sum() function, e.g.:

count = sum(1 for x in get_big_iterable() if should_keep(x))
like image 199
driedler Avatar answered Feb 09 '26 11:02

driedler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!