Question

According to Create a slice using a tuple, you can do it handy way:

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

But what I need is advanced ones:

a[5:]
a[:12]
a[:]
a[-1]
a[-2:]
a[:-2]
a[::-1]

How to do it with tuple and *args?

b = (5,:)
>>  File "<ipython-input-26-c4eae928199d>", line 1
>>    b = (5,:)
>>           ^
>>SyntaxError: invalid syntax
Était-ce utile?

La solution

For options that you want to omit, replace it with None. Generally, if any option is omitted, it default to None.

So option like slice(None, None, None) is equivalent to a[::]. Also remember the start and step arguments default to None.

For. ex.

a[5:]  -> b=(5,None,None)
a[:12] -> b=(None,12)
a[:]   -> b=(None,None)

One thing to note here is, slicing is different from indexing. So you cannot use the slice built-in if you intend to index.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top