在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ T not supported between instances of 'No

T not supported between instances of 'NoneType' and 'int'

# 返回素?cái)?shù)
def odd_iter():
    n = 1
    while True:
        n = n + 2
        yield

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)

def filter_primes():
    for num in primes():
        if num < 1000:  # 此處有類型轉(zhuǎn)換的問題
            print('current number is %d' % num)
        else:
            break
if __name__ == '__main__':
    filter_primes()

filter_primes 的 if 判斷的時(shí)出現(xiàn)了類型不匹配的 bug,求解?

TypeError: '<' not supported between instances of 'NoneType' and 'int'
回答
編輯回答
兔寶寶

錯(cuò)誤原因如 @nyrd33 所說

對(duì)於代碼有幾個(gè)建議:

  1. itertools 中的 count 可以讓我們省掉一個(gè) odd_iter

  2. prime 的上限值可以變成 filter_primes 的參數(shù)

  3. itertoolstakewhile 也滿好用的

代碼如下:

from itertools import takewhile, count

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

def primes():
    it = count(2)
    while True:
        n = next(it)
        yield n
        it = filter(not_divisible(n), it)
        
def filter_primes(k):
    for num in takewhile(lambda x: x < k, primes()):
        print('n={}'.format(num))
filter_primes(1000)
2017年5月14日 11:59
編輯回答
檸檬藍(lán)

錯(cuò)誤信息很清楚了,if 條件里是一個(gè) None 值在和 1000 比較,說明 primes() 產(chǎn)生了 None 。

primes() 的值都是 odd_iter() 產(chǎn)生的。

仔細(xì)看你的 odd_iter()yield 語句根本沒有返回任何值,自然是 None。

odd_iter()yield 應(yīng)當(dāng)返回 n。

2017年11月1日 23:18