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

如何在Python中将任意嵌套列表转换为指定格式的字符串?

Yes, a Generic Flattening Function Exists!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:01:57