是的,我知道这个主题之前已经被讨论过了:
Python成语链(扁平化)有限迭代对象的无限迭代?
在Python中扁平化一个浅列表
理解平展一个序列的序列吗?
我如何从列表的列表中创建一个平面列表?
但据我所知,所有的解决方案,除了一个,在像[[[1,2,3],[4,5]],6]这样的列表上失败,其中期望的输出是[1,2,3,4,5,6](或者更好,一个迭代器)。
我看到的唯一解决方案,适用于任意嵌套是在这个问题:
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
这是最好的方法吗?我是不是忽略了什么?任何问题吗?
没有装饰。只有发冷。
recursive_list_of_lists = [1,2,3,[1,2,[[3,4,[5]],7,0,1,10],100,[101,[101,[[101]],2]],0]]
k = []
def flatten(subl):
for i in subl:
if type(i) != type([1]):
k.append(i)
else:
flatten(i)
flatten(recursive_list_of_lists)
print(k)
[1, 2, 3, 1, 2, 3, 4, 5, 7, 0, 1, 10, 100, 101, 101, 101, 2, 0]
我很惊讶居然没人想到这一点。该死的递归,我没有得到这里的高级人员给出的递归答案。总之,这是我的尝试。警告是它非常特定于OP的用例
import re
L = [[[1, 2, 3], [4, 5]], 6]
flattened_list = re.sub("[\[\]]", "", str(L)).replace(" ", "").split(",")
new_list = list(map(int, flattened_list))
print(new_list)
输出:
[1, 2, 3, 4, 5, 6]