这个问题不同于Converting list of lists / nested lists to list of lists without nesting (这会产生一组非常具体的没有解决我情况的响应),也不同于许多“要列出的列表的扁平列表”的答案。
我想列出一个列表,其中一些是依次列出的列表和“扁平化”列表(而不仅仅是列表!)。
作为一个具体的例子,我想从以下几个方面着手:
my_list_of_lists = [[1, 2, 3], [[9, 10], [8, 9, 10], [3, 4, 6]], [11, 12, 13]]到这个
target_list_of_lists = [[1, 2, 3], [9, 10], [8, 9, 10], [3, 4, 6], [11, 12, 13]](从视觉意义上讲,我希望将外部列表中的所有[[和]]分别转换为[和]。)
发布于 2019-07-21 23:48:53
有一种方法可以做到:
def flatten(lst, dh=None):
# Added so user does not need to pass output list
if (dh is None):
dh = []
for elem in lst:
# Will not try to iterate through empty lists
if elem and (isinstance(elem[0], list)):
flatten(elem, dh)
else:
dh.append(elem)
return dh
my_list_of_lists = [[1, 2, 3], [[9, 10], [8, 9, 10], [3, 4, 6]], [11, 12, 13]]
target_list_of_lists = flatten(my_list_of_lists)
print(target_list_of_lists)输出:
[[1, 2, 3], [9, 10], [8, 9, 10], [3, 4, 6], [11, 12, 13]]这将适用于任何长度和深度的列表。
https://stackoverflow.com/questions/57137739
复制相似问题