Can python's slice notation be used outside of brackets?

大憨熊 提交于 2019-12-06 07:52:30

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!