Python access to multiple elements with discontiguous list

Python access to multiple elements with discontiguous list

Code

Python access list elements can be accessed according to a single index, and slices can be used to access contiguous elements, but when you want to access multiple discontinuous elements of the list, you can build an index list and then use the following list derivation.

list_1 = [1,2,3,4,5]
list_2 = [2,4]
list_3 = [list_1[i] for i in list_2]

Or use the .index () function

list_1 = [1,2,3,4,5]
list_2 = [2,4]
list_3 = [x for x in list_1 if list_1.index(x) in list_2]

Guess you like

Origin www.cnblogs.com/songbiao/p/12689249.html