Python 中数组的形状和大小
Muhammad Maisam Abbas
2023年1月30日

在本教程中,我们将讨论在 Python 中获取数组的形状和大小的方法。
在 Python 中使用 numpy.shape()
函数获取数组的形状
numpy.shape()
函数为我们提供了数组每个维度中的元素数量。numpy.shape()
返回一个元组,其中包含数组每个维度中的元素数。
以下代码示例向我们展示了如何使用 numpy.shape()
函数来获取 Python 中数组的形状。
import numpy
arr = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(numpy.shape(arr))
输出:
(2, 4)
在上面的代码中,我们首先使用 numpy.array()
函数初始化数组 arr
,然后使用 numpy.shape()
函数获得该数组的形状。
在 Python 中使用 numpy.size()
函数获取数组的大小
数组的大小是数组中元素的总数。numpy.size()
函数包返回给定数组的大小。下面的代码示例演示如何使用 numpy.size()
函数获取数组的大小。
import numpy
arr = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(numpy.size(arr))
输出:
8
在上面的代码中,我们首先使用 numpy.array()
函数初始化数组 arr
,然后使用 numpy.size()
函数获得该数组的大小。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn