Python iterator returning unwanted 'None'

后端 未结 2 1254
南旧
南旧 2021-01-24 05:12

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] Ca

2条回答
  •  粉色の甜心
    2021-01-24 05:58

    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
    

提交回复
热议问题