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

For example, I have a group of multidimensional arrays. I want to write a method to specify the slice size for this array, for example:

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

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

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

Any answer would be appreciated.

+4
source share
1 answer

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 obscuring the built-in functions by mistake.)

slice(x)equivalent to slice :x, and slice(x, y, z)-x:y:z

+6
source

Source: https://habr.com/ru/post/1651992/


All Articles