我在 python 3 中玩了一下 map() 和 filter() 函数。 我尝试获取一个列表并对其进行过滤,然后在过滤器对象上执行映射功能:
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))
结果是:
[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'>
当我注释掉 print(list(y)) 时,它突然运行良好。 你遇到过这个吗?我究竟做错了什么? 我在 ubuntu 上运行 python 3.6.3。
请您参考如下方法:
迭代器和生成器只能被消耗一次。当您调用 list(y) 时,它会生成序列中的所有值,然后耗尽。当您第二次尝试查看内容时,没有任何东西可以放弃,所以您得到一个空列表。
这可以更清楚地证明:
f = list(range(10))
print(f)
print('-----------')
y = filter(lambda a: a > 5, f)
print(list(y))
print(list(y))
给出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-----------
[6, 7, 8, 9]
[] # Nothing to yield
如果您想将值保留在 y 中,您需要将其分配给一个名称:
y = list(filter(lambda a: a > 5, f))
