在 Python 中获取列表形状

您所在的位置:网站首页 python查看list的大小 在 Python 中获取列表形状

在 Python 中获取列表形状

2023-07-14 20:04| 来源: 网络整理| 查看: 265

用 Python 中的 len() 函数获取一个列表的形状 用 Python 中的 numpy.shape() 方法获取列表的形状

在本教程中,我们将讨论在 Python 中获取列表形状的方法。

用 Python 中的 len() 函数获取一个列表的形状

len() 函数为我们提供了一个对象中元素的数量。下面的代码示例向我们展示了如何在 Python 中使用 len(x) 方法来获取一个列表的形状。

lista = [[1,2,3],[4,5,6]] arow = len(lista) acol = len(lista[0]) print("Rows : " + str(arow)) print("Columns : " + str(acol))

输出:

Rows : 2 Columns : 3

在上面的代码中,我们首先使用 len(lista) 得到 lista 中的行数,然后使用 len(lista[0]) 得到 lista 中的列数。

用 Python 中的 numpy.shape() 方法获取列表的形状

如果我们想让我们的代码能够处理任何多维列表,我们必须使用 numpy.shape() 方法。numpy.shape() 方法为我们提供了一个数组中每个维度的元素数量。numpy.shape() 返回一个包含数组每个维度元素数的元组。NumPy 包最初是设计用于数组,但也可以用于列表。

NumPy 是一个外部包,并没有预装在 Python 中。我们需要在使用它之前安装它。安装 NumPy 包的命令如下。

pip install numpy

下面的代码示例显示了我们如何使用 numpy.shape() 方法获得一个列表的形状。

import numpy as np lista = [1,2,3,4,5] listb = [[1,2,3],[4,5,6]] print("Shape of lista is : "+str(np.shape(lista))) print("Shape of listb is : "+str(np.shape(listb)))

输出:

Shape of lista is : (5,) Shape of listb is : (2, 3)

从上面的例子中可以看出,numpy.shape() 方法可以用于任何尺寸的列表。

토네이도를 ...

Please enable JavaScript

토네이도를 꿈꾸며 🌪️


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3