Python gets the data of the list by indexing the list

Method 1: [::2]

If the index is an arithmetic sequence: such as [2,4,6,8]
[::2]: take one every 2

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

Method 2: for loop:

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

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

Method 3: itemgetter function

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

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

Guess you like

Origin blog.csdn.net/qq_35759272/article/details/124433910