Create a slice using a tuple

孤街浪徒 提交于 2019-12-03 04:47:30

You can use Python's *args syntax for this:

>>> a = range(20)
>>> b = (5, 12)
>>> a[slice(*b)]
[5, 6, 7, 8, 9, 10, 11]

Basically, you're telling Python to unpack the tuple b into individual elements and pass each of those elements to the slice() function as individual arguments.

Foon

How about a[slice(*b)]?

Is that sufficiently pythonic?

slice takes up to three arguments, but you are only giving it one with a tuple. What you need to do is have python unpack it, like so:

a[slice(*b)]

Only one tiny character is missing ;)

In [2]: a = range(20)

In [3]: b = (5, 12)

In [4]: a[slice(*b)]
Out[4]: [5, 6, 7, 8, 9, 10, 11
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!