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
Another option is to use the sum() function, e.g.:
count = sum(1 for x in get_big_iterable() if should_keep(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With