American curl American curl - 1 month ago 5x
Python Question

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.


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