含字符串的Python递归生成器无限递归问题求解
Hey there! Great question—this is a super common gotcha when working with recursive flattening in Python, and it totally makes sense why you're hitting this issue. Let me break it down and show you how to fix it.
Why the Infinite Recursion Happens
Your original generator uses a try/except block to catch non-iterable values, but strings in Python are iterable (when you loop over a string, you get individual characters). The problem is that each character is also a string—so when your generator tries to flatten a string, it recursively calls itself on each character, which is another string, and this loop never ends. It never hits the TypeError because strings are always iterable!
Simple Fix: Explicitly Handle Strings
The easiest way to fix this is to add a check at the start of the function to catch strings (and maybe byte strings, if you need to handle those) and yield them directly without recursion:
def flatten(nested): # Handle strings (and byte strings) first to avoid infinite recursion if isinstance(nested, (str, bytes)): yield nested return try: for sublist in nested: for element in flatten(sublist): yield element except TypeError: yield nested
More Explicit Alternative (Using Iterable Check)
If you prefer a more explicit approach instead of relying on try/except, you can check if the input is an iterable (excluding strings/bytes) before recursing. This makes the logic clearer:
from collections.abc import Iterable def flatten(nested): # Skip recursion for strings and byte strings if isinstance(nested, (str, bytes)): yield nested return # Only recurse if the value is an iterable if isinstance(nested, Iterable): for sublist in nested: # Use yield from to simplify nested loops yield from flatten(sublist) else: yield nested
Testing It Out
If you run this with a list containing strings, it will work as expected:
# Example usage nested_list = [1, [2, "hello", [3, "world"]]] for item in flatten(nested_list): print(item) # Output: # 1 # 2 # hello # 3 # world
Don't worry about your English—you explained the problem perfectly clearly! Keep practicing, and you'll get the hang of these Python nuances in no time.
内容的提问来源于stack exchange,提问作者XiaoXin

