How to convert a 3D NumPy array to a list of lists of lists?
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics