-1

Assume I have a 3D list as following:

[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]], [[19, 20, 21], [22, 22, 23], [24, 25, 26]]]

I want to convert it to:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 22, 23], [24, 25, 26]]

I do not want to get lost inside of the for loops, is there a way this can be easily implemented?

Thanks in advance.

Katie
  • 21
  • 2

5 Answers5

0

Try summing the list with []:

sum(your_3d_list, [])

Attempt it Online!

zoomlogo
  • 173
  • 4
  • 14
0

You can use numpy module and reshape function:

import numpy as np
myList = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]], [[19, 20, 21], [22, 22, 23], [24, 25, 26]]]
array = np.array(myList)
array.reshape(9,3)

Output

array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15],
       [16, 17, 18],
       [19, 20, 21],
       [22, 22, 23],
       [24, 25, 26]])

You can use assert in order to make sure that this is the expected array:

expected = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 22, 23], [24, 25, 26]]
array = np.array(myList)
assert array.reshape(9,3).tolist() == expected

which works fine!

Note that, array.reshape(9,3) returns a numpy array and not a list. If you want to have the expected array as a list, you can use array.reshape(9,3).tolist()

array.reshape(9,3).tolist()

Output

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 22, 23], [24, 25, 26]]
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
0

Possible solution is the following:

lst = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]], [[19, 20, 21], [22, 22, 23], [24, 25, 26]]]

result = [item for subitem in lst for item in subitem]

print(result)

Prints

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 22, 23], [24, 25, 26]]

gremur
  • 1,645
  • 2
  • 7
  • 20
0

You can use

import itertools

library, which is a standard python library.

use it like this:

import itertools
array = itertools.chain.from_iterable(array)
array = list(array)

the output will be:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 22, 23], [24, 25, 26]]
The.Saeid
  • 36
  • 1
  • 3
0

You can loop through each 2d list in the 3d list, then loop through each 1d list in the 2d list

_3d_list = [[[1, 2, 3], [3, 2, 1], [1, 3, 5]], [[4, 5, 6], [6, 5, 4], [4, 6, 8]]]
final_list = []

for _2d_list in _3d_list:

    for _1d_list in _2d_list:

        final_list.append(_1d_list)

print(final_list)

Output:

[[1, 2, 3], [3, 2, 1], [1, 3, 5], [4, 5, 6], [6, 5, 4], [4, 6, 8]]
Kai
  • 115
  • 1
  • 2
  • 7