迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中 AttributeError: 'list' object has no attribute 'shape' 错误

作者:迹忆客 最近更新:2023/01/22 浏览次数:

Python“AttributeError: 'list' object has no attribute 'shape' ” 发生在我们尝试访问列表上的 shape 属性时。 要解决该错误,请将列表传递给 numpy.array() 方法以在访问 shape 属性之前创建一个 numpy 数组。

下面是一个产生上述错误的示例代码

my_list = [1, 2, 3]

# # ⛔️ AttributeError: 'list' object has no attribute 'shape'
print(my_list.shape)

Python 中 AttributeError- 'list' object has no attribute 'shape' 错误

要解决该错误,请将列表传递给 np.array() 方法来创建一个 numpy 数组。

import numpy as np

np_array = np.array([1, 2, 3])

print(np_array.shape)  # 👉️ (3,)

numpy.array 方法将类似数组的对象作为参数并创建一个数组。

在访问 shape 属性之前,我们还可以使用 numpy.asarray 方法将列表转换为 numpy 数组。

import numpy as np

np_array = np.asarray([1, 2, 3])

print(np_array.shape)  # 👉️ (3,)

或者,我们可以将列表直接传递给 numpy.shape 方法。

import numpy as np

array_shape = np.shape([1, 2, 3])
print(array_shape)  # 👉️ (3,)

print(np.shape([[1, 2]]))  # 👉️ (1, 2)

print(np.shape([0]))  # 👉️ (1,)

numpy.shape 方法将类似数组的对象作为参数并返回数组的形状。

形状元组的元素给出相应数组维度的长度。

如果需要获取列表的长度,请使用 len() 函数。

my_list = [[1, 2, 3], [4, 5, 6]]

# 👇️ get length of entire list
print(len(my_list))  # 👉️ 2

# 👇️ get length of list item at index 0
print(len(my_list[0]))  # 👉️ 3

len() 函数返回对象的长度(项目数)。

该函数采用的参数可以是序列(字符串、元组、列表、范围或字节)或集合(字典、集合或冻结集合)。

我们可以使用 dir() 函数查看对象具有的所有属性。

my_list = ['a', 'b', 'c']

# 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index',
#  'insert', 'pop', 'remove', 'reverse', 'sort' ...]
print(dir(my_list))

如果将一个类传递给 dir() 函数,它会返回该类属性的名称列表,并递归地返回其基类的属性。

如果我们尝试访问不在此列表中的任何属性,我们将收到“AttributeError: list object has no attribute”错误。


总结

Python“AttributeError: 'list' object has no attribute 'shape'” 发生在我们尝试访问列表上的 shape 属性时。 要解决该错误,请将列表传递给 numpy.array() 方法以在访问 shape 属性之前创建一个 numpy 数组。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便