yield break in Python

前端 未结 4 742
北海茫月
北海茫月 2021-01-30 16:18

According to answer to this question, yield break in C# is equivalent to return in Python. In the normal case, return indeed stops a gener

4条回答
  •  情深已故
    2021-01-30 16:46

    A good way to handle this is raising StopIteration which is what is raised when your iterator has nothing left to yield and next() is called. This will also gracefully break out of a for loop with nothing inside the loop executed.

    For example, given a tuple (0, 1, 2, 3) I want to get overlapping pairs ((0, 1), (1, 2), (2, 3)). I could do it like so:

    def pairs(numbers):
        if len(numbers) < 2:
            raise StopIteration
    
        for i, number in enumerate(numbers[1:]):
            yield numbers[i], number
    

    Now pairs safely handles lists with 1 number or less.

提交回复
热议问题