解决列表和元组多索引bug问题(TypeError: list indices must be integers or slices, not tuple)

在对列表和元组进行索引的时候,发现使用多维索引会出现以下bug:

TypeError: list indices must be integers or slices, not tuple

TypeError: tuple indices must be integers or slices, not tuple

list:
python 复制代码
list1 = [[1,2,3], [4,5,6]]
m1 = list1[1,0]
tuple:
python 复制代码
tuple1 = ((1,2,3), (4,5,6))
m2 = tuple1[0, 1]

问题原因:这是因为我们经常使用numpy库和torch库,里面的tensor类型和np类型是支持多索引的,而list和tuple不支持。因为list和tuple支持不同类型的数据同存,而numpy是不支持的,所以numpy可以进行多索引。例子如下:

我们使用list来查看里面数据的类型:

python 复制代码
list1 = [[1,2,3], ["test",5,6]]
print (type(list1[1][0]))
print (type(list1[0][0]))

可以看到list可以存储多种不同数据类型的数据。

我们使用numpy来进行测试:

python 复制代码
import numpy as np
np1 = np.array( [[1,2,3], ["test",5,6]])
print (type(np1[1][0]))
print (type(np1[0][0]))

可以看到输出结果如下:

我们可以看到,numpy在创建数组时,会自动的把数据类型统一,方便进行批量处理,即可以使用多索引。tensor也是同理

结论:

1.列表(List)和元组(Tuple)是内置的数据结构,可以包含不同类型的元素,并且长度可以动态改变,主要目的是提供灵活性和易用性。所以不支持多个索引

2.numpy是为了高校的数值计算而设计的,是一个固定大小和同质的多维数组。所以支持多个索引,方便数值计算

4.如果想要使用多个索引,可以把list转换为numpy来进行处理

python 复制代码
np1 = np.array( [[1,2,3], [4,5,6]]) #将list转换为numpy类型

测试不易,点个赞再走吧

相关推荐
疏狂难除9 小时前
X86-64 Assembly中printf 打印 float 和 double的bug的解决
bug·assembly
拂拉氏18 小时前
【项目分享-知识讲解】 C++标准库 list类的模拟实现
开发语言·c++·list·封装·stl标准库
nashane2 天前
HarmonyOS 6学习:指南针“文图反向”Bug修复——从“北偏东”变“北偏西”的坐标系纠错
学习·华为·bug·harmonyos
雨季mo浅忆2 天前
记录Vue3项目中的各类问题
前端·bug·vue3
csdn_aspnet2 天前
C# list集合 多属性排序
c#·list·linq·排序
hust_a3 天前
利用AI定位BUG的体验
bug
lcj25113 天前
【list】【手撕 STL】List 容器全解析!迭代器 / 增删改查 / 去重排序,面试必背的核心考点!
c++·面试·list
csdn_aspnet3 天前
C# 使用linq给List某个属性值赋值
c#·list·linq
lcj25114 天前
【list】手撕C++ list!从0到1实现双向链表,迭代器、const迭代器、模板全解析,面试官都惊呆了!
c++·笔记·链表·list
武壮4 天前
Redis 跳表(Skip List)实现
redis·bootstrap·list