Python | Ways to Convert a 3D list into a 2D list

Python | Ways to Convert a 3D list into a 2D list

Converting a 3D list (a list containing lists of lists) into a 2D list in Python can be done in several ways, depending on the intended result. Here are some ways to achieve this:

1. Using List Comprehensions

This is a straightforward method if you want to flatten only one level of the 3D list.

# Example 3D list
list_3d = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

# Flatten one level
list_2d = [item for sublist in list_3d for item in sublist]

print(list_2d)

2. Using itertools.chain()

If you have a 3D list and you want to flatten it by concatenating inner lists, you can use itertools.chain().

import itertools

list_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

# Flatten one level
list_2d = list(itertools.chain(*list_3d))

print(list_2d)

3. Using NumPy

If the sublists are all of the same length and you're dealing with numeric data, you can use NumPy to efficiently perform the conversion.

import numpy as np

list_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

# Convert to 2D array
array_2d = np.array(list_3d).reshape(-1, np.array(list_3d).shape[-1])

# Optionally convert back to list
list_2d = array_2d.tolist()

print(list_2d)

4. Using a Function (Recursive Approach)

If you need to flatten all levels and get a 2D list where each inner list was an element at the deepest level, you can use recursion.

def flatten_3d_list_to_2d(l):
    for el in l:
        if isinstance(el[0], list):  # Checks if the first element is a list
            yield from flatten_3d_list_to_2d(el)
        else:
            yield el

list_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
list_2d = list(flatten_3d_list_to_2d(list_3d))

print(list_2d)

5. Using More Itertools

The more_itertools library has a collapse() function that can flatten nested lists.

import more_itertools

list_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

# Flatten one level
list_2d = list(more_itertools.collapse(list_3d, levels=1))

print(list_2d)

Remember to install more_itertools before you use it:

pip install more_itertools

Choose the method that best suits your needs. The list comprehension is the most direct and often the easiest to read for simple flattening. NumPy is efficient for numerical computations, and the recursive function is most flexible for deeply nested and irregularly shaped lists.


More Tags

grep mplot3d unmount http-proxy-middleware contact-form-7 stacked-bar-chart insert restart uitableview vb.net

More Programming Guides

Other Guides

More Programming Examples