python3.x - Python中filter使用的一个疑问
阿神
阿神 2017-04-17 17:51:55
0
1
326

在学习廖雪峰的Python3.5 教程
filter 这一章有一个示例是“如何选出素数”,这里我有一些疑问,希望有人能够帮我解答,代码如下:

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

def _not_pisible(n):
    return lambda x: x%n > 0

def primes():
    yield 2
    it = _odd_iter();
    while True:
        n = next(it)
        yield n
        it = filter(_not_pisible(n), it)#怎么就实现了循环遍历 it了?

for n in primes():
    if n < 30:
        print(n)
    else:
        break

代码中我标有注释的一句话那里我能够明白是:

lambda x: x%n > 0

其实才是真正的 filter 的入参,而 x 指的是 filter 的另一个入参 it

我的疑问是,这里怎么就实现了将 it 中的数据遍历循环下去了呢?
换句话说,it 这个 Generator 里面到底是啥?

比如:

n = 3
yield 3
it = filter(lambda x: x % 3 >0, it)   # 这个里面it 到底有了哪些变化了?如何实现了过滤掉了素数?

it 等于了一个经过 filter 了个 it,虽然说是一种递归、或者嵌套的计算,但 Generator 是惰性的计算呀,这里不太理解如何能够不断的嵌套的

阿神
阿神

闭关修行中......

reply all(1)
迷茫

Correct your sentence

In fact, it is the real input parameter of filter, and x refers to another input parameter of filter it code>. filter的入参,而x指的是filter的另一个入参it

这里的it是一个生成器对象,而filter每次会得到一个由它生成的值。所以x指的不是it,只是it产生的一个值。

至于怎么实现将it中的数据遍历下去,这个很好解释。
我们知道filter接受两个参数functioniterable。而filter的功能就等价于(item for item in iterable if function(item)),它就是这么遍历完的。。。

it

The it here is a generator object, and filter will get a value generated by it every time. So x does not refer to it, but a value generated by it.

As for how to traverse the data in it, this is easy to explain.
We know that filter accepts two parameters function and iterable. The function of filter is equivalent to (item for item in iterable if function(item)), which is how it is traversed. . .

What is inside it? As you know, it's a generator object. After each call it will hang until the next time it is activated. 🎜
while True:
    n = next(it)
    yield n
    it = filter(_not_pisible(n), it)#怎么就实现了循环遍历 it了?
🎜The essence is to remove each prime number obtained from the generator. 🎜 🎜It is recommended that you take a look at the official documentation🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template