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

前端 未结 5 1516
面向向阳花
面向向阳花 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 10:14

    Converting a filter to a list will take extra memory, which may not be acceptable for large amounts of data. You can find length of the filter object without converting it to a list:

    sum(1 for _ in filter(lambda x: x > 3, n))

提交回复
热议问题