A detailed discussion of Python slicing

Source: Internet
Author: User

1. First of all, the most extensive use of slices, the reversal of strings

str = ' python ' str[::-1]

The result of the operation is Nohtyp

2. What are the features of the slices?

#带进步的切片 (step=10)
M[0:100:10]

#多维切片
Read some online blogs, this is what everyone wrote, but I run the time to find it is not right. Obviously the list in the direct transfer of a tuple must be wrong.
M[1:10,3:20]


#带进步值的多维切片
M[0:100:10.50:75:5]

#扩展切片分配

3. Boundary problems with slices

s = [1,2,3,4] s has an upper bound of 0, and the Nether is 4s[-100:100] returns [1,2,3,4]-100 and 100 are out of line, so return to the original ss[-100:-200] returns []. return [1,2,3,4]s[0:] return [1,2,3,4] because all are beyond the Nether s[100,200] return []s[:100]


4. Index of the most important slices

M[[start],[stop][,step]]


Step is positive index, negative is negative index

Sign of step
+: From left to right, start defaults to 0,stop default is index maximum value
-: From right to left, start defaults to index maximum, stop default is 0

The third parameter is step, if the number is positive, from the to after number.
If it is negative, the number from the back forward;
If not 1, it is the number of steps to jump, 1 means to go one step, jump 0 steps;

If the first parameter is not filled in, it is automatically set to the first parameter, which is either the index maximum or the index minimum based on the positive or negative judgment of the third parameter

A few simple examples

First define: S=[1,2,3,4,5,6,7,8,9,10]s[0:5:1] Results: [1,2,3,4,5]s[0,5,2]s[:5:2] The result is: [1,3,5]s[5:0:-1] Results: [5,4,3,2,1]s[9::-1] Results: [9,8,7,6,5,4,3,2,1]s[:6:-1] Results: [10,9,8,7]


Suitable for novice, welcome error correction.

A detailed discussion of Python slicing

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.