python - 如何在没有 try / except 的情况下终止生成器并引发 StopIteration?
问题描述
我正在尝试终止我创建的生成器函数的迭代,而不会在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)
解决方案
不需要终止生成器。当我们让它停止产生值时,它只会停止产生值。使用 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)
推荐阅读
- r - geom_raster 给出“条纹”结果
- reactjs - React 是使用类名管理多个主题的好方法吗?
- python - 如何获取 GitHub 存储库的贡献者总数?
- java - 在 macOS 上通过 brew 安装 JRE(但不是 JDK)
- angular7 - 如何将数据传递给自定义组件的标记?
- javascript - 如何禁用具有以逗号分隔的多个值的选项?
- android - Android WebView - 滚动条不填充 layout_height
- uinavigationcontroller - 如何从导航控制器中找到可见的 pushViewController?
- javascript - 在 nodeJs 中使用 require 的最佳方法
- json - ClickHouse Kafka Engine 可以使用压缩的 JSON 消息吗?