Extended Slices
Ever since Python 1.4, the slicing syntax has supported an optional third ``step'' or ``stride'' argument. For example, these are all legal Python syntax: L[1:10:2]
, L[:-1:1]
, L[::-1]
. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. Michael Hudson contributed a patch to fix this shortcoming.
For example, you can now easily extract the elements of a list that have even indexes:
>>> L = range(10) >>> L[::2] [0, 2, 4, 6, 8]
Negative values also work to make a copy of the same list in reverse order:
>>> L[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
This also works for tuples, arrays, and strings:
>>> s='abcd' >>> s[::2] 'ac' >>> s[::-1] 'dcba'
If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence:
>>> a = range(3) >>> a [0, 1, 2] >>> a[1:3] = [4, 5, 6] >>> a [0, 4, 5, 6]
Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing:
>>> a = range(4) >>> a [0, 1, 2, 3] >>> a[::2] [0, 2] >>> a[::2] = [0, -1] >>> a [0, 1, -1, 3] >>> a[::2] = [0,1,2] Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Deletion is more straightforward:
>>> a = range(4) >>> a [0, 1, 2, 3] >>> a[::2] [0, 2] >>> del a[::2] >>> a [1, 3]
One can also now pass slice objects to the __getitem__ methods of the built-in sequences:
>>> range(10).__getitem__(slice(0, 5, 2)) [0, 2, 4]
Or use slice objects directly in subscripts:
>>> range(10)[slice(0, 5, 2)] [0, 2, 4]
'미분류' 카테고리의 다른 글
Tracking algorithm(쓰는 중.) (0) | 2018.01.30 |
---|---|
VggNet - slim (0) | 2017.11.13 |
OpevCV HSV 색공간에 대해 알아보자 (0) | 2017.08.04 |
OpenCV YCbCr 색공간에 대해 알아보자 (0) | 2017.08.04 |
유사 연산자 엣지 검출 (0) | 2017.07.08 |