Python Daily class: Slice

Source: Internet
Author: User
Tags array length

class slice (stop) class slice (start, stop[, step])

Return a Slice object representing the set of indices specified byrange(start, stop, step). TheStartandStepArguments default toNone. Slice objects has read-only data attributesstart,stopandstepWhich merely return the argument values (or their default). They has no other explicit functionality; However they is used by numerical Python and all third party extensions. Slice objects was also generated when extended indexing syntax was used. For example:a[start:stop:step]Ora[start:stop, i]. Seeitertools.islice()For a alternate version that returns an iterator.

The cause of the problem

Today, when writing code, I see a more interesting wording. Suppose we have a list whose contents are a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. If we take it as a result of the reversal, it is common in our mind to think of nothing more than the reverse method. But it also has a way of saying: a[::-1], the result of the output is the opposite of the current result. In some cases, its application is more interesting. Just want to summarize this piece.

The application of slice in Python

In Python, slice access can be applied to lists, tuple, and string types that can traverse access. Slice itself means slicing and intercepting portions of these types that can traverse access. For example, the following code:

>>> L = Range (Ten)  >>> l  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  >>> l[1:5]  [1, 2, 3, 4]  

  

First, we generate a list from 0 to 9 through range (10). When [1:5] is taken in this list, the index 1 to 4 is returned. So, we find that the slice they take is a half-open half-closed interval. L[a:b]==> L[a, B).

In this case, we know the length of the list, and then take a section of them, if we do not understand the length of the list, or the length of the list is more difficult to get? In other languages, we might consider whether the list should have a property such as List.length. Here, there is another way to get:

>>> L[-1]  9  >>> l[1:-1]  [1, 2, 3, 4, 5, 6, 7, 8]  >>> l[2:-2]  [2, 3, 4, 5, 6 , 7]  

  

We can see if we want to take the last element in the list, you can use l[-1], if from the back forward, you can take l[-2], l[-3] ...

Since we mentioned earlier that the slice in the list is taken as an open interval behind closed, that is, when I am in l[a:b], the element whose index value is B is not included in the result. What if we want to include the values that follow?

This problem can be divided into several situations to consider, one is to add B itself is relatively small, then we take l[a:b+1] is good. For example, as follows:

>>> L[1:3]  [1, 2]  >>> l[1:4]  [1, 2, 3]  

If we want to include the index value of 3, we'll just use l[1:4]. So, what about the element at the end of the list? Using C, Java developers would think that this way would not result in access to the array out of bounds? Let's try it:

>>> Len (l)  >>> l[1:10]  [1, 2, 3, 4, 5, 6, 7, 8, 9]  >>> l[1:11]  [1, 2, 3, 4, 5, 6, 7, 8, 9]  >>> l[1:12]  [1, 2, 3, 4, 5, 6, 7, 8, 9]  

  

Len (l) returns the length of L. Our original subconscious thought that since the array length is 10, then the index maximum value we access is also l[9]. In fact, here in Python, you can list the access subscript values beyond the array length range, but only return the elements that can be traversed.

Of course, we have another way:

>>> l[1:]  [1, 2, 3, 4, 5, 6, 7, 8, 9]  

  

In this way, the elements that were previously indexed to the end of the array are all included.

In this way, we can include the entire array of elements in the following ways:

>>> l[0:]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  >>> l[:]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  >> ;> l  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  

From the way we used L[A:B] to access the elements, we've got A, b value that either satisfies 0<= a <= B or a >= 0 B < 0. In fact, the position of the corresponding element of a is always behind the corresponding position of B. So what happens if we turn their order upside down? For example:

>>> L[5:2]  []  >>> l[-1:3]  []  

  

Here, we find that if the actual element is taken first from the right and then to the left, it is not what we expected to return an inverted array, but an empty array. What's the use of this example? Don't worry, you'll know when you look at that section of the back.

Understanding Extended Slice

The front part is relatively good to understand. Now, if we have some other requirement, for example, if we want to return an array of elements with an odd index or an even number, what should we do?

There are several ways we can do this, one of which is to use extended slice, a typical solution:

>>> l[::2]  [02468]   >>> l[1::2]  [1357 9 ]  >>>   

What is the previous style with two colons?

In fact, the two parts of the first colon separated by our side are the same as the previous meaning, that is, the interval of the intermediate elements of the array. So the first l[::2] is preceded by the entire array of elements. And the latter part refers to a step size. What does that mean? That is, since we specified the entire array earlier, it is starting from 0, and then each time we access the adjacent elements. When set to 2, it accesses the element behind and its distance is 2, not the directly adjacent element. In this way, it is easy to understand L[1::2], which is the element from the beginning of element 1 to the end of the collection of elements to take the interval of 2.

At this point, it is very close to our understanding of the eccentric l[::-1 in front of us. The step in front of us is to set the step size to a positive number, so in the collection of elements it represents the element from left to right that takes the specified step. What if we set the step to a negative number? Let's see:

>>> l[1:9:-1]  []  >>> l[9:1:-1]  [9, 8, 7, 6, 5, 4, 3, 2]  

  

With this part of the code above, I believe it is not difficult to understand. We take the interval [1, 9), and the result is an empty collection when the step is 1. And when we take 9 to 1, the step is-1 out of the reverse array. This is because if we specify a negative step size, then it must be the same as the interval specified by the data. That is, if the interval we specified earlier is from the small index of the array to the large index, then the step size I specify must also be small to large. Therefore, a positive number must be. And if the interval we specify is from behind, then the step must be specified as a negative number. Otherwise, the returned result is an empty array.

Summarize

With so much discussion ahead, let's look at an array of slice accesses. They are just a few cases, in the case of l[a:b], you must ensure that the index position where a is located before, b where the index position is behind, otherwise the returned result is empty. In the case of l[a:b:step], we must first determine the direction according to the position of a, B, a in front, b after the words, step should be positive, otherwise it should be negative. If these conditions are not met, an empty array is returned. In other words, look at the position of a, B to determine the direction, do not make a directional error, otherwise naught:)

Python Daily class: Slice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.