【问题标题】:"Flatten" list containing lists of lists to list of lists“扁平化”列表包含列表列表到列表列表
【发布时间】:2019-11-29 22:34:37
【问题描述】:

这个问题与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]]

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

【问题讨论】:

  • 我不认为建议的副本是正确的,因为这个问题不想完全展平列表,只需删除一些嵌套层,同时保留其他层。

标签: python list


【解决方案1】:

这是一种方法:

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

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

【讨论】:

  • 也许更干净,可以在末尾添加默认值:def flatten(lst, dh = None): #... dh = [] if dh is None else dhreturn dh,以便最终用户没有设置输出缓冲区?
  • 小心——您需要 `=None` 和条件,以便您在每次顶级调用时开始一个新列表。否则:def test(a = []): a.append(45); return a; test() #=> [45]; test() #=> [45, 45]
  • :) (我们都这样做......前几天我在其中一个上花费的时间比我想承认的要长......)
  • 请注意,我的实际列表中有 [] 在列表列表中(例如,my_list_of_lists = [[1, 2, 3], [], [[9, 10], [], [8, 9, 10], [3, 4, 6]], [11, 12, 13]])。这破坏了解决方案,但将条件更改为 if elem and (isinstance(elem[0], list)): 使其工作。
猜你喜欢
  • 2016-01-14
  • 2012-07-01
  • 2017-09-24
  • 1970-01-01
  • 2010-12-13
  • 2017-02-27
  • 2021-03-06
  • 2021-05-06
相关资源
最近更新 更多