深度阅读

How to get shape of an array in python

作者
作者
2023年08月22日
更新时间
9.56 分钟
阅读时间
0
阅读量

To get the shape of an array in Python, you can use the shape attribute for numpy arrays or the shape method for regular Python lists. Here are some examples:

For a numpy array:

import numpy as np
my_array = np.array([[1, 2, 3], [4, 5, 6]])
print(my_array.shape)

This will output (2, 3), which indicates that the array has 2 rows and 3 columns.

For a regular Python list:

my_list = [[1, 2], [3, 4], [5, 6]]
n_rows = len(my_list)
n_cols = len(my_list[0])
print((n_rows, n_cols))

This will output (3, 2), which indicates that the list has 3 rows and 2 columns.

In both cases, the shape information is returned as a tuple, where the first element represents the number of rows and the second element represents the number of columns (or dimensions for numpy arrays with more than 2 dimensions).

Note that the shape attribute and method are read-only, so you cannot change the shape of an array or list using them.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。