Python:list()函数弄乱了map() [英] Python: list() function messes up map()

查看:83
本文介绍了Python:list()函数弄乱了map()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 3上使用了map()filter()函数. 我试图获取一个列表并对其进行过滤,然后在过滤器对象上执行地图功能:

I was playing a bit with the map() and filter() functions at python 3. I tried to take a list and filter it and then on the filter object to do a map function:

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.

When I comment out the print(list(y)) it suddenly works well. Did you encounter this? What am I doing wrong? I run python 3.6.3 on ubuntu.

推荐答案

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

Iterators and generators can only be consumed once. When you call list(y), it yields all of the values in the sequence and is then exhausted. When you try to see the contents a second time, there is nothing left to yield, so you get an empty list back.

以下内容更清楚地证明了这一点:

This is more-clearly demonstrated with:

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中,则需要将其分配给名称:

If you want to keep the values in y you will need to assign it to a name:

y = list(filter(lambda a: a > 5, f))

这篇关于Python:list()函数弄乱了map()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆