【问题标题】:How to terminate a generator without try / except and raise StopIteration?如何在没有 try / except 的情况下终止生成器并引发 StopIteration?
【发布时间】:2021-02-27 23:59:04
【问题描述】:

我正在尝试终止我创建的生成器函数的迭代,而不会在遇到StopIteration 时立即终止程序。我知道我可以使用try / except 语句来捕获抛出的异常,但是有没有办法在不抛出异常的情况下终止生成器函数?

我的代码:

def isPalindrome(num):
    if num == int(str(num)[::-1]):
        return True
    return False

def palindrome_special():
    num = 0
    while True:
        if isPalindrome(num):
            yield num
            if len(str(num)) == 10:
                raise StopIteration
            num = 10 ** len(str(num)) #If palindrome is encountered, a reassignment takes place to calculate the next palindrome containing 1 more digit
        num = num + 1

for i in palindrome_special():
    print(i)

【问题讨论】:

  • 不清楚你在问什么,因为你没有终止生成器。除了通过调用next 来响应您对另一个元素的请求之外,它不会做任何事情。如果你不打那个电话,它什么也做不了。
  • 此外,例外是next 如何区分生成器生成的实际值和生成器没有剩余可生成的值。
  • 此外,抛出异常绝对没有错,只要您捕获并适当地处理它们。其实很pythonic到ask for forgiveness instead of permission
  • 您对例外有什么看法?

标签: python python-3.x exception iterator generator


【解决方案1】:

生成器不需要终止。当我们让它停止产生值时,它只会停止产生值。使用 if 语句重写代码并在生成器函数中使用 break 即可。

    def isPalindrome(num):
        if num == int(str(num)[::-1]):
            return True
        return False
    
    def palindrome_special():
        num = 0
        while True:
            if isPalindrome(num):
                if len(str(num)) <= 10: #If statement
                    yield num
                else: #condition that terminates the generation of values
                    break
                num = 10 ** len(str(num))
            num = num + 1
    
    for i in palindrome_special():
        print(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2020-05-07
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    相关资源
    最近更新 更多