如何在python中展平列表?

时间:2016-01-02 15:27:13

标签: python list

我有一个输出解决方案的程序,这些解决方案是数字列表:

    [[1, [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]], [2, [[1, 4], [2, 3], [3, 2], [4, 1]]], [3, [[1, 3], [2, 2], [3, 1]]], [4, [[1, 2], [2, 1]]], [5, [[1, 1]]]]

我希望将其转化为:

    [[1,1,5],[1,2,4],[1,3,3],[1,4,2],[1,5,1],[2,1,4],[2,2,3],[2,3,2],[2,4,1],[3,1,3],[3,2,2],[3,3,1],[4,1,2],[4,2,1],[5,1,1]]

基本上,整个列表中的每个术语都以数字为首,它构成了具有该数字的所有可能解决方案的第一项,然后以下列表指出要添加的内容。

4 个答案:

答案 0 :(得分:0)

这应该有效。它适用于您至少拥有的示例。

result = [[[i[0]] + j for j in i[1:][0] ] for i in arr][0]

答案 1 :(得分:0)

介绍两个功能:mergeflatten

第二个功能取自here

def flatten(lst):
    return [item for sublist in lst for item in sublist]

第一个函数定义为:

def merge(lst):
    return [[lst[0]] + x for x in flatten(lst[1:])]

然后打电话给他们:

 s = [[1, [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]], [2, [[1, 4], [2, 3], [3, 2], [4, 1]]], [3, [[1, 3], [2, 2], [3, 1]]], [4, [[1, 2], [2, 1]]], [5, [[1, 1]]]]
 print flatten([merge(x) for x in s])

输出是:

[[1, 1, 5], [1, 2, 4], [1, 3, 3], [1, 4, 2], [1, 5, 1], [2, 1, 4], [2, 2, 3], [2, 3, 2], [2, 4, 1], [3, 1, 3], [3, 2, 2], [3, 3, 1], [4, 1, 2], [4, 2, 1], [5, 1, 1]]

答案 2 :(得分:0)

items = [[1, [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]], [2, [[1, 4], [2, 3], [3, 2], [4, 1]]], [3, [[1, 3], [2, 2], [3, 1]]], [4, [[1, 2], [2, 1]]], [5, [[1, 1]]]]
flat_items = []
for item in items:
    leading = item[0]
    for i in item[1]:
        flat_items.append([leading]+i)
print(flat_items)

答案 3 :(得分:0)

另一种解决方案可以根据需要为您提供输出:

def flatten(lst):
    result = []
    for i in lst:
        for j in i[1]:
            pair = j[:]
            pair.insert(0, i[0])
            result.append(pair)
    return result