David Bots
David Bots

Reputation: 13

iteration over python nested lists

I need to convert list 'a' to list 'b' , how to do it?

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

Upvotes: 1

Views: 73

Answers (5)

Tae Choi
Tae Choi

Reputation: 35

I suggest a loop method.

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

Upvotes: 0

Vasilis G.
Vasilis G.

Reputation: 7846

Another way of achieving concatenation of two lists is the following:

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)

Output:

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

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

I suggest the follow list comprehension:

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

It is equivalent to the following nested for-loop:

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

Although, I would write it more like:

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

Upvotes: 2

Joe Iddon
Joe Iddon

Reputation: 20414

You can use a neat trick with sum() to join nested lists:

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

Just to make it clearer why this works, consider the following example:

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

Or you could use the more efficient itertools.chain_from_iterable method:

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

Upvotes: 1

Sheldore
Sheldore

Reputation: 39042

You can use list comprehension: This assumes that you have only two sub-sublists within each sublist. Since you are very clear in your input and output, it does what you want

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

Output

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

Upvotes: 1

Related Questions