Discuss / Python / 求助!想不明白例子中一个问题

求助!想不明白例子中一个问题

Topic source

donkeycity

#1 Created at ... [Delete] [Delete and Lock User]
def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it) # 构造新序列

最后一句改成 it = filter(lambda x: x % n > 0, it) 不可以吗?我试了下,输出的还是奇数序列,但不知道问题出在哪……

Kerwin0621

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

当然不可以,it这里指的是奇数生成序列,而你带入的这个lambda是奇数筛选序列功能。你把这个功能替换了it,它就只会筛选奇数了

donkeycity

#3 Created at ... [Delete] [Delete and Lock User]
def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(lambda x: x % n > 0, it) # 构造新序列

lambda里是x%n,不是x%2,是筛掉it中能整除n的数啊,为啥不行……

确实不行lambda函数可以查一下他的特性。https://www.cnblogs.com/lybolg/p/12521851.html

lambda用过即销,所以不能进栈调用

必须赋给一个变量成为一个函数

donkeycity

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

如果那里我写it = filter(lambda x: x % 3 > 0, it)是能够成功把it序列中能整除3的元素滤掉的。

为什么写it = filter(lambda x: x % n > 0, it)就不行呢。


  • 1

Reply