迭代python嵌套列表

问题描述 投票:1回答:5

我需要将列表'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,]]]
python list nested nested-lists
5个回答
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]]]

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
投票

您可以使用列表推导:这假设您在每个子列表中只有两个子子列表。由于您的输入和输出非常清晰,它可以满足您的需求

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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.