简体   繁体   English

Python:迭代器返回None

[英]Python: Iterator returns None

Here is my code: 这是我的代码:

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))

An example of usage: 用法示例:

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

The output should be: 输出应该是:

[4]

But actual output is: 但实际输出是:

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

Why does it happen? 为什么会这样?

Your problem is your implementation of __next__ . 你的问题是__next__的实现。 When Python calls __next__ , it will always expect a return value . 当Python调用__next__它总是期望返回值 However, in your case, it looks like you may not always have a return value each call. 但是,在您的情况下,看起来您可能并不总是每次调用都有返回值。 Thus, Python uses the default return value of a function - None : 因此,Python使用函数的默认返回值 - None

You need some way to keep program control inside of __next__ until you have an actually return value. 你需要一些方法来保持程序控制在__next__直到你有一个实际的返回值。 This can be done using a while -loop: 这可以使用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

Wrap it with while so that your method doesn't return a value until you found one: 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

Things working with iterators call __next__ expecting it to return a value, but the method returns a value only under a condition, otherwise it reaches the end of the method and it returns None . 使用迭代器的事情调用__next__期望它返回一个值,但该方法仅在条件下返回一个值,否则它到达方法的末尾并返回None

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

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