Discuss / Python / Fitler _not_divisible的另一种写法,新手更容易理解。

Fitler _not_divisible的另一种写法,新手更容易理解。

Topic source

大爷洒

#1 Created at ... [Delete] [Delete and Lock User]

以下方法的另一种写法,新手更容易理解。

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



def not_divisible(n):
    def fun1(x):
        return x % n > 0
    return fun1

请问,为什么这里不需要把x写成输入参数呢?

就 

def _not_divisible(n,x):

大爷洒

#4 Created at ... [Delete] [Delete and Lock User]

filter() 的第一个参数就是带有一个参数的Fun(x),第二个参数是List,Filter 会把List的每个元素传给Fun(x)。

_not_divisible 其实不是Filter的Fun参数,真正的参数是_not_divisible里面的 Lambda 匿名函数,所以不需要传x,而 _not_divisible(n) 的实参N并不是Fitler传的,是上面已经定义好的变量。

也就是这句n = next(it)

def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it) 

donkeycity

#5 Created at ... [Delete] [Delete and Lock User]

最后一句如果it = filter(lambda x: x % n > 0, it)可以吗,我试了下不对,但是感觉这么写也是为了每次把it序列中能整除n的数筛掉啊

大爷洒

#6 Created at ... [Delete] [Delete and Lock User]
it = filter(lambda x: x % n > 0, it)

这个Lambda 相当于 

def fn(x):
  return x % n > 0 

直接把Fn给了Filter,参数X是有了,Fn函数内并没有N啊,所以一定错误。

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

这个实际函数 _not_divisible 返回值也是个函数,只不过是个匿名函数。 你可以看一下 函数式编程 -> 返回函数 那一章节。

donkeycity

#7 Created at ... [Delete] [Delete and Lock User]

我想就不用_not_divisible(n)函数,只是把it = filter(_not_divisible(n), it)改成it = filter(lambda x: x % n > 0, it),并不会报错,而且n的值应该能从上面的yield n拿过来。

但实验结果输出的并不是素数序列。您用空的话可以试一下,谢谢~


  • 1

Reply