Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list [a, b, c] to python slice index[:a, :b :c]?

For example, I'm having a group of multi-dimension arrays. I want to write a method to specify the size of the slice for this array such as:

slice = data[:a, :b, :c]

Because I could only get a list of [a, b, c]. I want to know how can I convert this list to slice index. Or is there a way to connect the list with slice index so as to operate this array as:

list = [a, b, c]
slice = data[list]

Any reply would be appreciated.

like image 588
American curl Avatar asked Aug 22 '16 04:08

American curl


1 Answers

Use the slice() function.

my_list = [a, b, c]
my_slices = tuple(slice(x) for x in my_list)
my_slice = data[my_slices]

(I updated the variable names to avoid shadowing the builtins by mistake.)

slice(x) is equivalent to the slice :x, and slice(x, y, z) is x:y:z

like image 155
lazy dog Avatar answered Nov 14 '22 22:11

lazy dog