繁体   English   中英

Python:迭代器返回None

[英]Python: Iterator returns None

这是我的代码:

class Prizes(object):
    def __init__(self, purchases, n, d):
        self.p = purchases
        self.n = n
        self.d = d
        self.x = 1

    def __iter__(self):
        return self

    def __next__(self):
        print(self.x)

        if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0:
            self.x = self.x + 1
            return self.x - 1
        elif self.x > len(self.p):
            raise StopIteration

        self.x = self.x + 1

def superPrize(purchases, n, d):
  return list(Prizes(purchases, n, d))

用法示例:

superPrize([12, 43, 13, 465, 1, 13], 2, 3)

输出应该是:

[4]

但实际输出是:

[None, None, None, 4, None, None].

为什么会这样?

你的问题是__next__的实现。 当Python调用__next__它总是期望返回值 但是,在您的情况下,看起来您可能并不总是每次调用都有返回值。 因此,Python使用函数的默认返回值 - None

你需要一些方法来保持程序控制在__next__直到你有一个实际的返回值。 这可以使用while -loop来完成:

def __next__(self):
    while True:
        if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0:
            self.x = self.x + 1
            return self.x - 1
        elif self.x > len(self.p):
            raise StopIteration
        self.x = self.x + 1

while包装它,这样你的方法就不会返回值,直到找到一个:

def __next__(self):
    while True:
        if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0:
            self.x = self.x + 1
            return self.x - 1
        elif self.x > len(self.p):
            raise StopIteration

        self.x = self.x + 1

使用迭代器的事情调用__next__期望它返回一个值,但该方法仅在条件下返回一个值,否则它到达方法的末尾并返回None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM