문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top