80
>>> n = [1,2,3,4]

>>> filter(lambda x:x>3,n)
<filter object at 0x0000000002FDBBA8>

>>> len(filter(lambda x:x>3,n))
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    len(filter(lambda x:x>3,n))
TypeError: object of type 'filter' has no len()

取得したリストの長さを取得できませんでした。だから私はこのように変数に保存しようとしました...

>>> l = filter(lambda x:x>3,n)
>>> len(l)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    len(l)
TypeError: object of type 'filter' has no len()

ループを使用する代わりに、これの長さを取得する方法はありますか?

4

5 に答える 5

33

これは古い質問ですが、この質問にはmap-reduceイデオロギーを使用した回答が必要だと思います。だからここに:

from functools import reduce

def ilen(iterable):
    return reduce(lambda sum, element: sum + 1, iterable, 0)

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

nこれは、コンピュータのメモリに収まらない場合に特に有効です。

于 2017-06-04T07:14:42.297 に答える