Python iterator returning unwanted 'None'

后端 未结 2 1263
南旧
南旧 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:44

    Functions return None if you don't have an explicit return statement. That's what happens in __next__ when if (self.purchase[old])%(self.d) == 0: isn't true. You want to stay in your __next__ until it has a value to return.

    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):
            while self.i < self.length:
                old = self.i
                self.i += self.n
                if (self.purchase[old])%(self.d) == 0:
                    return old+1
            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))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题