问题
Within brackets, python's slice shorthand auto-generates tuples of slice objects:
class Foo(object):
def __getitem__(self, key):
print key
Foo()[1::, 2:20:5]
This prints (slice(1, None, None), slice(2, 20, 5))
. As far as I can tell, however, this shorthand doesn't work outside brackets.
Is there any way to use slice shorthand in other contexts? I could define a dummy object that simply returns whatever it is passed to __getitem__
-- that would at least give me a way to generate slice tuples using the shorthand syntax. Is there a more pythonic way?
回答1:
NumPy has an s_ object that will do this for you:
>>> np.s_[2::2]
slice(2, None, 2)
You can easily make your own version of this simply by setting s_ = Foo()
and then using s_
whenever you want to create a slice easily.
回答2:
What you see printed out is actually a good clue. You can create slice objects directly through the slice() global function. These can then be passed used to index from lists.
s = slice(1, 10, 2)
numbers = list(range(20))
print numbers[s]
print numbers[1:10:2]
This will print the same result twice, [1, 3, 5, 7, 9].
The slice instances have a few attributes and methods. You can look at help(slice) to see more.
来源:https://stackoverflow.com/questions/11980524/can-pythons-slice-notation-be-used-outside-of-brackets