How to find the length of a “filter” object in python

前端 未结 5 1505
面向向阳花
面向向阳花 2020-12-08 09:18
>>> n = [1,2,3,4]

>>> filter(lambda x:x>3,n)


>>> len(filter(lambda x:x>3,n))
Traceback         


        
5条回答
  •  一生所求
    2020-12-08 09:59

    This is an old question, but I think this question needs an answer using the map-reduce ideology. So here:

    from functools import reduce
    
    def ilen(iterable):
        return reduce(lambda sum, element: sum + 1, iterable, 0)
    
    ilen(filter(lambda x: x > 3, n))
    

    This is especially good if n doesn't fit in the computer memory.

提交回复
热议问题