How to convert a 3D NumPy array to a list of lists of lists?
NumPy: Interoperability Exercise-16 with Solution
Write a NumPy program to convert a 3D NumPy array to a list of lists of lists and print the result.
Sample Solution:
Python Code:
import numpy as np
# Create a 3D NumPy array
array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("Original 3D NumPy array:",array_3d)
print(type(array_3d))
# Convert the 3D NumPy array to a nested list of lists of lists
list_of_lists = array_3d.tolist()
# Print the list of lists of lists
print("\nlist of lists of lists:")
print(list_of_lists)
print(type(list_of_lists))
Output:
Original 3D NumPy array: [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] <class 'numpy.ndarray'> list of lists of lists: [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]] <class 'list'>
Explanation:
- Import NumPy Library: Import the NumPy library to work with arrays.
- Create 3D NumPy Array: Define a 3D NumPy array with some example data.
- Convert to Nested List: Use the tolist() method of the NumPy array to convert it into a nested list of lists of lists.
- Print List of Lists: Output the resulting nested list to verify the conversion.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to read a CSV file into a NumPy array and print it?
Next: How to convert a list of lists of lists to a 3D NumPy array and print it?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/convert-a-3d-numpy-array-to-a-list-of-lists-of-lists.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics