gpt4 book ai didi

python - "Flatten"list 包含lists of lists to lists of lists

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:10 30 4
gpt4 key购买 nike

这个问题不同于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]]

(在视觉上,我想把所有[[ and ]] inside outer list都变成[] 分别。)

最佳答案

这是一种方法:

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]]

这适用于任何长度和深度的列表。

关于python - "Flatten"list 包含lists of lists to lists of lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137739/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com