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

前端 未结 5 1503
面向向阳花
面向向阳花 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条回答
  •  -上瘾入骨i
    2020-12-08 10:01

    You have to iterate through the filter object somehow. One way is to convert it to a list:

    l = list(filter(lambda x: x > 3, n))
    
    len(l)  # <--
    

    But that might defeat the point of using filter() in the first place, since you could do this more easily with a list comprehension:

    l = [x for x in n if x > 3]
    

    Again, len(l) will return the length.

提交回复
热议问题