Python迭代器返回不需要的'无' [英] Python iterator returning unwanted 'None'

查看:146
本文介绍了Python迭代器返回不需要的'无'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的迭代器在输出中返回额外的'None'。对于下面的参数/示例,我得到 [None,4,None] 而不是所需的 [4] 任何人都可以解释为什么我得到额外的无,我怎么能解决它?打印出来的'返回'只出现一次所以我假设只有一个项目应该附加到返回的调用函数。

Why is my iterator returning extra 'None' in the output. For the parameters/example below, I am getting [None,4,None] instead of the desired [4] Can anyone explain why I am getting the extra None and how I can fix it? The print out 'returning' only appears once so I am assuming only one item should be appended to the returning calling function.

代码:

class Prizes(object):
    def __init__(self,purchase,n,d):
        self.purchase = purchase
        self.length = len(purchase)
        self.i = n-1
        self.n = n
        self.d = d

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < self.length:
            old = self.i
            self.i += self.n
            if (self.purchase[old])%(self.d) == 0:
                print("returning")
                return old+1
        else:
            raise StopIteration

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

purchases = [12, 43, 13, 465, 1, 13]
n = 2
d = 3
print(superPrize(purchases, n, d))

输出:

returning
[None, 4, None]


推荐答案

正如评论中的人所指出的那样,你的行 if(self.purchase [old])%(self.d) == 0:导致函数返回而没有任何返回值。如果没有提供返回值暗示无。在返回或提高 StopIteration 之前,您需要某种方式继续通过列表到达通过此测试的下一个可用值。一个简单的方法就是添加一个额外的 else 子句来再次调用 self .__ next __()测试失败。

As people in the comments have pointed out, your line if (self.purchase[old])%(self.d) == 0: leads to the function returning without any return value. If there is no return value supplied None is implied. You need some way of continuing through your list to the next available value that passes this test before returning or raising StopIteration. One easy way of doing this is simply to add an extra else clause to call self.__next__() again if the test fails.

def __next__(self):
        if self.i < self.length:
            old = self.i
            self.i += self.n
            if (self.purchase[old])%(self.d) == 0:
                print("returning")
                return old+1
            else:
                return self.__next__()
        else:
            raise StopIteration

这篇关于Python迭代器返回不需要的'无'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆