Python:list()函数搞砸了map()

Ari*_*abo 1 python dictionary list filter python-3.x

我正在使用python 3中的函数map()filter()函数.我尝试获取一个列表并对其进行过滤,然后在过滤器对象上执行map函数:

f = list(range(10))
print(f)
print('-----------')
y = filter(lambda a: a > 5, f)
print(list(y))
print(y)
print(type(y))
print('-----------')
x = map(lambda value: value+1, y)
print(list(y))
print(y)
print(type(y))
print('-----------')
print(list(x))
print(x)
print(type(x))
Run Code Online (Sandbox Code Playgroud)

结果是:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-----------
[6, 7, 8, 9]
<filter object at 0x7f46db255ac8>
<class 'filter'>
-----------
[]
<filter object at 0x7f46db255ac8>
<class 'filter'>
-----------
[]
<map object at 0x7f46db3fc128>
<class 'map'>
Run Code Online (Sandbox Code Playgroud)

当我发表评论时,print(list(y))它突然运作良好.你遇到过这个吗?我究竟做错了什么?我在ubuntu上运行python 3.6.3.

rog*_*osh 10

迭代器和生成器只能被使用一次.当您调用时list(y),它会生成序列中的所有值,然后耗尽.当您尝试再次查看内容时,没有任何内容可以产生,因此您将获得一个空列表.

这更清楚地表现为:

f = list(range(10))
print(f)
print('-----------')
y = filter(lambda a: a > 5, f)
print(list(y))
print(list(y))
Run Code Online (Sandbox Code Playgroud)

这使:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-----------
[6, 7, 8, 9]
[] # Nothing to yield
Run Code Online (Sandbox Code Playgroud)

如果要保留值,y则需要将其分配给名称:

y = list(filter(lambda a: a > 5, f))
Run Code Online (Sandbox Code Playgroud)