如何让生成器表达式耗尽后停止打印,避免StopIteration异常
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

