Using an iterator in python?

前端 未结 4 916
[愿得一人]
[愿得一人] 2021-01-21 16:05

I have just learned about iterators in Python however I am having a hard time implementing them.

I am trying to write a class to so that this loop works:



        
4条回答
  •  猫巷女王i
    2021-01-21 16:22

    There is probably a much cleaner way of doing this, but here is a quick stab:

    class OddNumbers:
    
        def __init__(self, number):
            self.number = number
    
        def __iter__(self):
            self.current = self.number
            return self
    
        def __next__(self):
            if self.current > 0:
                if self.current % 2 == 0:
                    self.current -= 1
                self.current -= 1
                return self.current + 1
            raise StopIteration
    

提交回复
热议问题