Sliced, like bread, given a few knives, cut into slices, which can be made into toast or even better as a sandwich:

Lists, tuples, and strings can all be sliced to produce sub-fragments, and slicing is much more powerful than you might think. You can take values and assign values.

Ignore the last element

Slices are described with subscripts and colons, such as s[2:13]. For 2, 3… The sequence of, 12, expressed as [2, 13), left closed and right open, is more reasonable than [2, 12] and (1, 13) for the following reasons:

  1. The upper limit minus the lower limit is equal to the number of elements, for example13 minus 2 is 11, there are exactly 11 elements.
  2. Contiguous ranges have no overlap, for example[2, 13)[13, 25)It’s two consecutive ranges, and 13 will only be in the last one.

The subscripts start at 0

For 10 elements, it is more reasonable to write [0, 10) than [1, 11) for the following reasons:

  1. N elements, [0, N) is more concise than [1, N+1), so you don’t need +1.

  2. The subscript of an element is equal to the number of elements that precede it.

    0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ^ we have four elements in front of itCopy the code

Handy slices

The above two mathematical theories bring many benefits to the use of slicing:

  • When there is only the last position information, you can quickly see that there are several elements, such as my_list[:3] returning three elements.

  • When both start and end positions are visible, you can quickly calculate the length using stop-start, such as my_list[1:3] of length 2.

  • Use any of the subscripts to cut the sequence into two non-overlapping parts, just write my_list[:x] and my_list[x:], for example

    >>> my_list = [10.20.30.40.50.60]
    >>> my_list[:3]
    [10.20.30]
    >>> my_list[3:]
    [40.50.60]
    Copy the code

Range in Python also ignores the last element and the subscript starts at 0.

Slice interval

In addition to s[a:b], there is also a third subscript S [A :b:c], which means that s is evaluated with an interval of C between A and B. C can also be negative, and negative value means the reverse value. Such as:

>>> s = "bicycle"
>>> s[::3]
"bye"
>>> s[::-1]
"elcycib"
>>> s[::-2]
"eccb"
Copy the code

A: B: C: START :stop:step

The syntax is so simple that you can see it’s the magic of Python! When evaluating s[a:b:c], Python actually calls S. __getitem__(slice(a, B, C)), familiar recipe, familiar taste. Slice (a, b, c) is a slice object returned by a:b:c in []. Slice () is a built-in Python function, as shown in this example:

invoice = "Mini Kit $34.95 1 $34.95"
SKU = slice(0.8)
print(invoice[SKU])
Copy the code

Slice assignment

A powerful feature of slicing is to assign values to slices. If we place the slice to the left of an assignment statement or use it as the object of a DEL operation, we can graft, cut, or modify sequences in place. Example:

>>> l = list(range(10))
>>> l
[0.1.2.3.4.5.6.7.8.9]
>>> del l[5:7]
>>> l
[0.1.2.3.4.7.8.9]
>>> l[3:2] = [11.22]
>>> l
[0.1.2.11.22.3.4.7.8.9]
>>> l[2:5] = [100]
>>> l
[0.1.100.3.4.7.8.9]
Copy the code

Note that if the assigned object is a slice, then the right side of the assignment statement must be an iterable, even if there is only a single value, otherwise an error is reported:

>>> l[2:5] = 100
Traceback (most recent call last):
  File "<input>", line 1.in <module>
TypeError: can only assign an iterable
Copy the code

Multidimensional slice

In addition to one-dimensional slicing, Python also supports multidimensional slicing, which is shown in multidimensional arrays. NumPy is a Python third-party library that provides higher-order arrays, making Python the mainstream language for scientific computing applications. Example:

>>> import numpy
>>> a = numpy.arange(12)
>>> a
array([ 0.1.2.3.4.5.6.7.8.9.10.11])
>>> a.shape
(12.)>>> a.shape = 3.4
>>> a
array([[ 0.1.2.3],
       [ 4.5.6.7],
       [ 8.9.10.11]])
>>> a[:, 1]
array([1.5.9])
>>> a[1:2.2:3]
array([[6]])
>>> a[1:3.2:4]
array([[ 6.7],
       [10.11]])
Copy the code

In NumPy, the ellipsis… Used as a shortcut for slicing a multidimensional array, if x is a four-dimensional array, then x[I,… Is short for x[I, : : :], for example:

>>> a.shape = 2.2.3
>>> a
array([[[ 0.1.2],
        [ 3.4.5]],
       [[ 6.7.8],
        [ 9.10.11]]])
>>> a[:, :, 1]
array([[ 1.4],
       [ 7.10]])
>>> a[..., 1]
array([[ 1.4],
       [ 7.10]])
Copy the code

summary

This article introduced Python’s powerful slicing operations. Because the last element is ignored and subscripts start at 0, slicing is particularly handy. In addition to the start and end, you can also set the interval between slicing. Slice assignment is another powerful feature of slicing. Note that the right side of the assignment statement must be an iterable.

References:

Smooth Python

Blog. Wz52. Cn/archives / 17…