问题
I have a class holding data (a numpy ndarray) that includes a method storing the data to a mat-file (using scipy.io.savemat). The data can be very large, so I may only want to store a segment of the data. Therefore I pass a slice-object, like this:
def write_mat(self, fn, fields=None, sel=None):
# (set fields and sel to sensible values if None)
scipy.io.savemat(fn, dict(data=self.data[fields][sel]))
Here, fields
may be a list of strings (for self.data
is a structured array), and sel
is a slice-object. Of course, I cannot directly pass the slice-syntax into write_mat
: obj.write_mat(fn, fields, [::10])
is a SyntaxError. Of course, I can pass in slice(None, None, 10)
instead, but I don't like this solution very much.
Is there any builtin convenience object that will allow me to create a slice-object from the slice-syntax? Of course, it's easy to implement:
In [574]: class Foo:
...: def __getitem__(self, item):
...: return item
...:
In [578]: slicer = Foo()
In [579]: slicer[::100]
Out[579]: slice(None, None, 100)
but even for something easy to implement there may already be a more standard solution. Is there? By standard I mean existing inside Python, numpy, or scipy.
回答1:
The answer on Passing Python slice syntax around to functions is correct, but as you're already using NumPy you can use np.s_:
import numpy as np
np.s_[1:2:3]
Out[1]: slice(1, 2, 3)
来源:https://stackoverflow.com/questions/15161856/slice-syntax-to-object