You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让生成器表达式耗尽后停止打印,避免StopIteration异常

How to Stop a Generator Expression Without Triggering StopIteration in Python

Hey there! Let's fix that StopIteration issue you're hitting with your generator expression. The core problem here is how you're trying to loop over genPairs—let's break this down and fix it step by step.

Why Your Current Code Fails

Your while genPairs: loop keeps running because a generator object is always truthy in Python, even when it's exhausted. So the loop never exits on its own, and eventually next(genPairs) has no more items to yield, triggering the StopIteration exception.

Also, your earlier attempt to use len() on a generator won't work—generators are lazy and don't store all their items in memory, so they don't have a length you can access directly with len().

Simple Fix: Use a for Loop Instead

The easiest and most Pythonic way to iterate over a generator (or any iterable) is to use a for loop. It automatically handles the StopIteration exception under the hood, stopping gracefully once all items are yielded.

Replace your last three lines:

genPairs = (item for item in letterTable)
while genPairs:
    print(next(genPairs))

With this:

genPairs = (item for item in letterTable)
for pair in genPairs:
    print(pair)

Or even simpler—you don't need to create genPairs at all; you can iterate directly over letterTable:

for pair in letterTable:
    print(pair)

Alternative: Catch the StopIteration Exception

If you really need to use a while loop (though the for loop is better practice), you can explicitly catch the exception to break the loop:

genPairs = (item for item in letterTable)
while True:
    try:
        print(next(genPairs))
    except StopIteration:
        break

Bonus: Simplify Your Entire Code

You can streamline your code a bit too—instead of manually counting letters with a generator, you could use collections.Counter which does this work for you:

import re
from collections import Counter

print("Input your string")
regex = re.compile('[^a-zA-Z]')
inStr = input()
newString = regex.sub("", inStr).lower()

# Counter handles the letter counting automatically
letter_counts = Counter(newString)

# Iterate over sorted items directly
for letter, count in sorted(letter_counts.items()):
    print((letter, count))

This does the same thing as your original code but with less boilerplate, and it avoids manual generator handling entirely.

内容的提问来源于stack exchange,提问作者Podo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:38:47