如何在Python中将任意嵌套列表转换为指定格式的字符串?
Absolutely—recursion is perfect for handling arbitrary nested lists like this. Here's a straightforward, reusable function that will flatten any level of nesting, convert all elements to strings, and let you format them into your desired comma-separated string.
Basic Version (For Lists Only)
This function focuses specifically on lists, which matches your example scenario:
def flatten_nested_list(nested_list): for element in nested_list: # If the element is another list, recursively flatten it if isinstance(element, list): yield from flatten_nested_list(element) # Otherwise, convert the element to a string and yield it else: yield str(element)
How to Use It
Let’s test it with your example code:
b = 15 my_list = [1,2,3,4,[5,6,7,8,[9,["a",b,"c"],10,11]]] # Flatten the list and join elements with ", " flat_string = ', '.join(flatten_nested_list(my_list)) print(flat_string)
This will output:1, 2, 3, 4, 5, 6, 7, 8, 9, a, 15, c, 10, 11
(Note: Your example output included "b" instead of 15, but since b is a variable holding the value 15, the function correctly uses the actual value of the variable when processing the list.)
Enhanced Version (Handles All Iterables Except Strings)
If you want to support other iterable types (like tuples or sets) without accidentally splitting strings into individual characters, use this expanded version:
from collections.abc import Iterable def flatten_any_iterable(nested): for element in nested: # Check if it's an iterable but NOT a string/bytes (to preserve text) if isinstance(element, Iterable) and not isinstance(element, (str, bytes)): yield from flatten_any_iterable(element) else: yield str(element)
Why This Works
Recursion lets us handle unknown nesting depth effortlessly: every time we hit a nested list (or iterable), we dive into it and repeat the process until we reach individual elements. Converting each element to a string ensures everything can be joined into a single, uniform comma-separated string.
This function works no matter how deep your lists are—whether it’s 2 levels or 200.
内容的提问来源于stack exchange,提问作者Saleh Ahmadzada

