Python 打印不带方括号的列表编号

Python 打印不带方括号的列表编号,python,python-3.x,Python,Python 3.x,例如,我有许多方括号的数字列表,我想打印没有括号的代码 L = [[[1, 2, 3], [4, 5]], 6] output: [1,2,3,4,5,6] 如果您只想使用x正确平衡打印: x=[1,[9,[[[[[2]]]]]],[[[2],[12,[2]],[10]] print('[' + ''.join(c for c in str(x) if not c in '[]') +']') 输出: [1, 9, 2, 2, 12, 2, 10] [1, 2, 3, 4, 5, 6]

例如,我有许多方括号的数字列表,我想打印没有括号的代码

L = [[[1, 2, 3], [4, 5]], 6]
output:
[1,2,3,4,5,6]
如果您只想使用x正确平衡打印:

x=[1,[9,[[[[[2]]]]]],[[[2],[12,[2]],[10]]
print('[' + ''.join(c for c in str(x) if not c in '[]') +']') 
输出:

[1, 9, 2, 2, 12, 2, 10]
[1, 2, 3, 4, 5, 6]

这是临时的。在许多方面,第一个x是一个更自然的解决方案。

使用递归函数:

def flatten(list):
    if type(list)==list:
        answer = []
        for item in list:
            answer += flatten(item)
        return answer
    else:
        return list

print(flatten(x))
说明:

递归函数将逐步分解列表,对于每个子列表,它将在较小的子列表上调用自己。

一行递归:

def flat(l):
    return [i for ll in l for i in (flat(ll) if type(ll) is list else [ll])]
还有一个测试:

>>> flat([[[1, 2, 3], [4, 5]], 6])
[1, 2, 3, 4, 5, 6]

一个更黑客的解决方案可能包括使用正则表达式:

import re
L = [[[1, 2, 3], [4, 5]], 6]
new_s = list(map(int, re.findall('\d+', str(L))))
输出:

[1, 9, 2, 2, 12, 2, 10]
[1, 2, 3, 4, 5, 6]

这篇文章并不含糊,但它几乎是重复的。首先展平列表是一个自然的第一步,特别是因为生成的展平列表可能有其他用途。可能重复的@Eylandesc但OP需要外括号,因此不是真正的重复我想要的函数应该是“,”。连接?可能的解决方案:打印[+x.replace[,.replace],+]@这也是一种自然的方法