加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python:迭代器返回None

发布时间:2020-12-16 22:32:56 所属栏目:Python 来源:网络整理
导读:这是我的代码: 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] % s

这是我的代码:

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,d):
  return list(Prizes(purchases,d))

用法示例:

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

输出应该是:

[4]

但实际输出是:

[None,None,4,None].

为什么会这样?

最佳答案
你的问题是__next__的实现.当Python调用__next__时,它总是期望返回值.但是,在您的情况下,看起来您可能并不总是每次调用都有返回值.因此,Python使用函数的默认返回值 – 无:

你需要一些方法来保持程序控制在__next__中,直到你有一个实际的返回值.这可以使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读