python通过索引列表去获取列表的数据

方法1:[::2]

如果索引是有等差数列:比如[2,4,6,8]
[::2]:每隔2个取一个

a = [1,2,3,4,5]
print(a[::2])
  • 输出
[1, 3, 5]

方法2:for循环:

b=[0,2]
a = ['elem0','elem1','elem2'] 

sublist = [a[i] for i in b]

方法3:itemgetter函数

from operator import itemgetter
b=[0,2]
a = ['elem0','elem1','elem2']

print(itemgetter(*b)(a))
  • 输出:
('elem0', 'elem2')

猜你喜欢

转载自blog.csdn.net/qq_35759272/article/details/124433910