python3初学者,遇到一个关于print()问题,请大家不吝赐教



我在学习map()函数这块时,使用number_filter的值,如果在number_filter值生成之后,不执行print函数,然后再map()中调用,结尾就可以打印出来,但是如果number_filter值生成之后,打印了一次,再在map()中调用,就打印出来[]空,不知道什么原因,请求指导,谢谢。

Jason990420
最佳答案
>>> number_list = range(1, 11)
>>> number_filter = filter(lambda b:b%2==0, number_list)
>>> print(type(number_filter))
<class 'filter'>

class filter(object)

filter(function or None, iterable) –> filter object

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

Python的迭代器协议使用的两个阶段

  • 首先通过iter()调用设置并检索迭代器对象
  • 然后通过next()反复从其获取值。

为了表示迭代结束,Python 迭代器只是引发了内置StopIteration异常,以表明没有更多的值可用于迭代。

>>> number_list = range(1, 11)
>>> number_filter = filter(lambda b:b%2==0, number_list)
>>> print(list(number_filter))    # list get all content of iterator
[2, 4, 6, 8, 10]
>>> next(number_filter)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
StopIteration
2周前 评论
hanfei (楼主) 2周前
讨论数量: 1
Jason990420
>>> number_list = range(1, 11)
>>> number_filter = filter(lambda b:b%2==0, number_list)
>>> print(type(number_filter))
<class 'filter'>

class filter(object)

filter(function or None, iterable) –> filter object

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

Python的迭代器协议使用的两个阶段

  • 首先通过iter()调用设置并检索迭代器对象
  • 然后通过next()反复从其获取值。

为了表示迭代结束,Python 迭代器只是引发了内置StopIteration异常,以表明没有更多的值可用于迭代。

>>> number_list = range(1, 11)
>>> number_filter = filter(lambda b:b%2==0, number_list)
>>> print(list(number_filter))    # list get all content of iterator
[2, 4, 6, 8, 10]
>>> next(number_filter)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
StopIteration
2周前 评论
hanfei (楼主) 2周前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!