python嵌套列表上的迭代

时间:2018-08-19 13:40:47

标签: python list nested nested-lists

我需要将列表“ a”转换为列表“ b”, 怎么做?

a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]

b = [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12,]]]

5 个答案:

答案 0 :(得分:2)

我建议理解以下列表:

In [1]: a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
   ...:

In [2]: [[[a for sub in nested for a in sub]] for nested in a]
Out[2]: [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]

它等效于以下嵌套的for循环:

result = []
for nested in a:
    _temp = []
    for sub in nested:
        for a in sub:
            _temp.append(a)
    result.append([_temp])

尽管,我会这样写:

result = []
for nested in a:
    _temp = []
    for sub in nested:
        _temp.extend(sub)
    result.append([_temp])

答案 1 :(得分:1)

您可以使用列表理解:假定每个子列表中只有两个子子列表。由于您在输入和输出中都非常清楚,它可以满足您的要求

a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = [[c[0] + c[1]] for c in a ]
print (b)

输出

[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]

答案 2 :(得分:1)

您可以对sum()使用巧妙的技巧来加入嵌套列表:

[[sum(l, [])] for l in a]
#[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]

只是为了更清楚地说明其工作原理,请考虑以下示例:

>>> sum([[1,2], [3,4]], [])
[1, 2, 3, 4]

或者您可以使用更有效的itertools.chain_from_iterable方法:

flatten = itertools.chain.from_iterable
[[list(flatten(l))] for l in a]
#[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]

答案 3 :(得分:0)

另一种实现两个列表串联的方法是:

a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]

b = list(map(lambda elem: [[*elem[0], *elem[1]]],a))
print(b)

输出:

[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]

答案 4 :(得分:0)

我建议使用循环方法。

a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = []
for i in a:
    new_j = []
    for j in i:
        new_j.extend(j)
    new_i = [new_j]
    b = b + [new_i]
b