Discuss / Python / 问个问题

问个问题

Topic source

def _not_divisible(n): return lambda x: x % n > 0 这段代码x是接收什么参数的,我能理解是接收序列中每个值 但是怎么传递进来的呢?这个n难道不是接收序列中的每个值吗

等价于

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

注意一下filter函数用法,下面的函数_not_divisible(n)作用it序列中的每一个,即上边函数的x输入.

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

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

其实 结果是个返回函数,参数是x。

困扰好久,在回来复习看到返回函数才明白其中道理

智仝障

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

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)# 构造新序列(去掉了第一个数和第一个数的倍数) 参数x接收的是it序列中的一个元素; 参数n接收的是it序列中的第一个元素(n = next(it)); 每调用一次primes(),都会返回一个筛选出来的素数n,并重新生成一个去掉素数n及其倍数的it序列; _not_divisible()的作用是向匿名函数lambda传递序列的第一个元素n; 匿名函数lambda的作用是传入序列的一个元素x,并返回满足x % n > 0的x

智仝障

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

lambda中接收的参数x,是通过filter()传递的

函数名是_not_divisible(n),函数体是lambda x: x % n > 0。 所以while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) 中,先要给定n,那么_not_divisible(n)就是确定的了, 然后放入到filter()中,filter()就用_not_divisible(n)作用于序列(貌似称为Iterator更专业)it.

貌似称为 返回动态函数更适合。

为了便于理解,我们先把

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

改写为:

def _not_divisible(n): def panduan(x): return x%n!=0 return panduan

你问的问题取决你怎么理解 _not_divisible(n)

实际上_not_divisible(n)返回的是panduan这个函数,而且,注意,返回的是给上层_not_divisible传递了n这个参数的panduan函数,每次n的变化,都会产生一个不同n的panduan函数,n就是生成序列里面第一个确保是素数的数字,用来当分母筛选it这个序列。

例子:当n=3时,it_not_divisible(n)相当于:n=3的panduan(),而it生成所有序列都将放入panduan()里面,执行 it[x]%3>0 的判断,返回为真的it[x],则filter成为新的it。

it = filter(_not_divisible(n),it) 实际执行过程是: 1.执行_not_divisible(n),返回匿名函数lambda x: x%n>0 所以filter中的规则其实是这个匿名函数 2.执行it = filter(lambda x: x%n >0, it) 即用filter对it做过滤。x是it中的每一个元素。


  • 1

Reply