简体   繁体   中英

How can I convert a 3D list into a 2D list in python?

This is the code that I have:

[[[3], [4]], [[5], [6]], [[7], [8]]]

How can I change it into:

[[3], [4], [5], [6], [7], [8]]

?

You want to flatten a single level of the input list, try this solution using a list comprehension:

lst = [[[3], [4]], [[5], [6]], [[7], [8]]]
[e for sl in lst for e in sl]
=> [[3], [4], [5], [6], [7], [8]]

try this:

import numpy as np
a = np.array([[[3],[4]],[[5],[6]],[[7],[8]]])
b = a.reshape(6,1)

A uncompressed or long way:

l3d = [[[3], [4]], [[5], [6]], [[7], [8]]]
l2d = []
for e1 in l3d:
   for e2 in e1:
      l2d.append(e2)
# Provided list
lst = [[[3], [4]], [[5], [6]], [[7], [8]]]

# To do this we are going to import chain from itertools
from itertools import chain

final = list(chain(*lst))

print(final)  # Output: [[3], [4], [5], [6], [7], [8]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM