简体   繁体   English

Python:过滤器和生成器

[英]Python: filter and generator

Here is the code:这是代码:

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
def _not_divisible(n):
    return lambda x: x % n > 0
def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it) 
        yield n
        it = filter(_not_divisible(n), it)
for n in primes():
    if n < 10:
        print(n)
    else:
        break

1. I want to know what is the process about this practice , i was stuck on the 1.我想知道这个练习的过程是什么,我被困在了

it = _odd_iter()

and

it = filter(_not_divisible(n), it)

Is the it stored value like list or something?它的存储值是像列表还是什么?

For the first part, filter() returns a filter object(which is an iterator) and not a list对于第一部分,filter() 返回一个过滤器对象(它是一个迭代器)而不是一个列表

>>> filter(lambda x : x < 5 , [1,2,3,4,5,6,7,8])
<filter object at 0x7eff8b5922e8>
>>> list(filter(lambda x : x < 5 , [1,2,3,4,5,6,7,8]))
[1, 2, 3, 4]

You can check python docs for more information.您可以查看python 文档以获取更多信息。 This is only in Python3.这仅在 Python3 中。

The second part is similar.第二部分类似。 filter() will iterate through the generator and create another iterator which contains the filtered data. filter() 将遍历生成器并创建另一个包含过滤数据的迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM