python根据一个list的index获取list

假如能够获得某list的某一堆的index,存在list里面

list不支持这样查询:

ls=[1,2,3,4,5,6,7,8,9,0]
ls[2,3,6]
##或者
ls=[1,2,3,4,5,6,7,8,9,0]
ls[[2,3,6]]

都会报错:

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

 或者

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

正确的方式其实也很简单:

ls=[1,2,3,4,5,6,7,8,9,0]#list
index=[2,3,6]#index list 
[ls[i]for i in index]

运行结果:

[3, 4, 7]

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/109308777