将列表列表展平到列表列表中

时间:2015-10-26 20:47:08

标签: python list python-2.7 flatten

我已经搜索了SO如何拼合列表列表(例如:Making a flat list out of list of lists in Python),但我发现的解决方案都没有将列表列表列表简化为列表列表

我有:

my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]

我想:

my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ]

该解决方案也适用于浮动列表。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

这是fl00r递归答案的由内而外的版本,与OP之后的内容更为吻合:

def flatten(lists,n):
    if n == 1:
        return [x for xs in lists for x in xs]   
    else:
        return [flatten(xs,n-1) for xs in lists]


>>> flatten(my_list,1)
[[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
>>> flatten(my_list,2)
[[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]

答案 1 :(得分:0)

您可以使用此递归子例程

def flatten(lst, n):
  if n == 0:
    return lst

  return flatten([j for i in lst for j in i], n - 1)

mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]
flatten(mylist, 1)
#=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
flatten(mylist, 2)
#=> [1, 2, 3, 4, 5, 9, 8, 9, 10, 3, 4, 6, 1]

答案 2 :(得分:0)

对于这种特殊情况,

In [1]: [sum(x,[]) for x in my_list]
Out[1]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]

是最短也是最快的方法:

In [7]: %timeit [sum(x,[]) for x in my_list]
100000 loops, best of 3: 5.93 µs per loop