【发布时间】:2019-01-21 22:41:35
【问题描述】:
我有一个很大的Iterable。
我想使用filter() 函数对其进行过滤。
我如何计算(以某种优雅的方式)过滤了多少项目?
(同样的问题可能适用于map()、reduce() 等)
当然我可以做到:
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))
filter() 有可能吗?
items = filter(should_keep, get_big_iterable())
for item in items:
#... using values here ..
#possible count not filtered items here too?
我不应该迭代两次,并想使用filter() 或类似的解决方案
【问题讨论】:
标签: python python-3.x dictionary filter iterator