


A thorough understanding of python slicing operations in one article
In the process of using Python to solve various practical problems, we often encounter the situation of extracting partial values from an object. The slicing operation is specifically used to complete this operation. powerful weapon. Theoretically, as long as the conditional expression is appropriate, any target value can be obtained through a single or multiple slicing operations. The basic syntax of slicing operations is relatively simple, but if the internal logic is not thoroughly understood, errors can easily occur, and such errors are sometimes hidden deep and difficult to detect. This article summarizes various situations of slicing operations through detailed examples. If there are any errors or shortcomings, please correct me!
1. The indexing method of Python's slicable objects
The indexing method of Python's slicable objects includes: positive index and negative index.
As shown in the figure below, take a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as an example:
2. General method of Python slicing operation
A complete slicing expression contains two ":", used to separate three parameters (start_index, end_index, step), When there is only one ":", the default third parameter step=1.
Basic expression for slicing operation: object[start_index : end_index : step]
step: Both positive and negative numbers can be used. Its absolute value determines the "step size" when cutting data, and The positive and negative signs determine the "cutting direction". Positive means taking the value "from left to right", and negative means taking the value "from right to left". When step is omitted, the default is 1, that is, the value is taken in increments of 1 from left to right. "The cutting direction is very important!" "The cutting direction is very important!" "The cutting direction is very important!" Say important things three times!
start_index: Indicates the starting index (including the index itself); when this parameter is omitted, it means starting from the "endpoint" of the object. As for whether it starts from the "starting point" or the "endpoint", it is determined by step The positive and negative parameters determine the step. If the step is positive, it starts from the "starting point", and if it is negative, it starts from the "end point".
end_index: Indicates the end index (excluding the index itself); when this parameter is omitted, it means that the data is obtained until the "endpoint". As for whether it reaches the "starting point" or the "endpoint", it is also determined by the step parameter. Determined by positive or negative, if the step is positive, it will go to the "end point", and if it is negative, it will go to the "starting point".
3. Detailed examples of Python slicing operations
The following examples are based on the list a = [0, 1, 2, 3, 4, 5, 6, 7, 8 , 9] For example:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1. Cut a single value
>>> a[0] 0 >>> a[-4] 6
2. Cut a complete object
>>> a[:] # 从左往右 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[::] # 从左往右 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[::-1] # 从右往左 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
3. The case where start_index and end_index are both positive ( ) indexes
>>> a[1:6] # step=1,从左往右取值,start_index=1到end_index=6同样表示从左往右取值。 [1, 2, 3, 4, 5] >>>a[1:6:-1] # step=-1,决定了从右往左取值,而start_index=1到end_index=6决定了从左往右取值,两者矛盾。 >>> [] # 输出为空列表,说明没取到数据。 >>>a[6:1] # step=1,决定了从左往右取值,而start_index=6到end_index=1决定了从右往左取值,两者矛盾。 >>> [] # 同样输出为空列表。 >>>a[:6] # step=1,从左往右取值,从“起点”开始一直取到end_index=6。 >>> [0, 1, 2, 3, 4, 5] >>>a[:6:-1] # step=-1,从右往左取值,从“终点”开始一直取到end_index=6。 >>> [9, 8, 7] >>>a[6:] # step=1,从左往右取值,从start_index=6开始,一直取到“终点”。 >>> [6, 7, 8, 9] >>>a[6::-1] # step=-1,从右往左取值,从start_index=6开始,一直取到“起点”。 >>> [6, 5, 4, 3, 2, 1, 0]
Related recommendations: "Python Video Tutorial"
4. The case where start_index and end_index are both negative (-) indexes
>>>a[-1:-6] # step=1,从左往右取值,而start_index=-1到end_index=-6决定了从右往左取值,两者矛盾。 >>> [] >>>a[-1:-6:-1] # step=-1,从右往左取值,start_index=-1到end_index=-6同样是从右往左取值。 >>> [9, 8, 7, 6, 5] >>>a[-6:-1] # step=1,从左往右取值,而start_index=-6到end_index=-1同样是从左往右取值。 >>> [4, 5, 6, 7, 8] >>>a[:-6] # step=1,从左往右取值,从“起点”开始一直取到end_index=-6。 >>> [0, 1, 2, 3] >>>a[:-6:-1] # step=-1,从右往左取值,从“终点”开始一直取到end_index=-6。 >>> [9, 8, 7, 6, 5] >>>a[-6:] # step=1,从左往右取值,从start_index=-6开始,一直取到“终点”。 >>> [4, 5, 6, 7, 8, 9] >>>a[-6::-1] # step=-1,从右往左取值,从start_index=-6开始,一直取到“起点”。 >>> [4, 3, 2, 1, 0]
5. The case of start_index and end_index positive ( ) negative (-) mixed index
>>>a[1:-6] # start_index=1在end_index=-6的左边,因此从左往右取值,而step=1同样决定了从左往右取值。 >>> [1, 2, 3] >>>a[1:-6:-1] # start_index=1在end_index=-6的左边,因此从左往右取值,但step=-则决定了从右往左取值,两者矛盾。 >>> [] >>>a[-1:6] # start_index=-1在end_index=6的右边,因此从右往左取值,但step=1则决定了从左往右取值,两者矛盾。 >>> [] >>>a[-1:6:-1] # start_index=-1在end_index=6的右边,因此从右往左取值,而step=-1同样决定了从右往左取值。 >>> [9, 8, 7]
6. Continuous slicing operation
>>>a[:8][2:5][-1:] >>> [4]
is equivalent to:
a[:8]=[0, 1, 2, 3, 4, 5, 6, 7] a[:8][2:5]= [2, 3, 4] a[:8][2:5][-1:] = 4
Theoretically, unlimited continuous slicing is possible operation, as long as the last returned object is still a non-empty sliceable object.
7. The three parameters of the slicing operation can be expressed using the expression
>>>a[2+1:3*2:7%3] # 即:a[2+1:3*2:7%3] = a[3:6:1] >>> [3, 4, 5]
8. Slicing operations of other objects
The previous slicing operation instructions take list as an example. , but in fact there are many data types that can be sliced, including tuples, strings, etc.
>>> (0, 1, 2, 3, 4, 5)[:3] # 元组的切片操作 >>> (0, 1, 2) >>>'ABCDEFG'[::2] # 字符串的切片操作 >>>'ACEG' >>>for i in range(1,100)[2::3][-10:]: # 利用range函数生成1-99的整数,然后取3的倍数,再取最后十个。 print(i, end=' ') >>> 72 75 78 81 84 87 90 93 96 99
4. Commonly used slicing operations in Python
Take a list: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] is the description object
1. Take the even position
>>>b = a[::2] [0, 2, 4, 6, 8]
2. Take the odd position
>>>b = a[1::2] [1, 3, 5, 7, 9]
3.Copy the entire object
>>>b = a[:] # ★★★★★ >>>print(b) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>print(id(a)) # 41946376 >>>print(id(b)) # 41921864 >>>b = a.copy() >>>print(b) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>print(id(a)) # 39783752 >>>print(id(b)) # 39759176 需要注意的是:[:]和.copy()都属于“浅拷贝”,只拷贝最外层元素,内层嵌套元素则通过引用,而不是独立分配内存。 >>>a = [1,2,['A','B']] >>>print('a={}'.format(a)) a=[1, 2, ['A', 'B']] # 原始a >>>b = a[:] >>>b[0] = 9 # 修改b的最外层元素,将1变成9 >>>b[2][0] = 'D' # 修改b的内嵌层元素 >>>print('a={}'.format(a)) # b修改内部元素A为D后,a中的A也变成了D,说明共享内部嵌套元素,但外部元素1没变。 a=[1, 2, ['D', 'B']] >>>print('b={}'.format(b)) # 修改后的b b=[9, 2, ['D', 'B']] >>>print('id(a)={}'.format(id(a))) id(a)=38669128 >>>print('id(b)={}'.format(id(b))) id(b)=38669192
4.Modify a single Element
>>>a[3] = ['A','B'] [0, 1, 2, ['A', 'B'], 4, 5, 6, 7, 8, 9]
5. Insert element
>>>a[3:3] = ['A','B','C'] [0, 1, 2, 'A', 'B', 'C', 3, 4, 5, 6, 7, 8, 9] >>>a[0:0] = ['A','B'] ['A', 'B', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6. Replace part of element
>>>a[3:6] = ['A','B'] [0, 1, 2, 'A', 'B', 6, 7, 8, 9]
5. Summary
(1) start_index, end_index, and step can be both positive and negative, or a mixture of positive and negative can be used. But one principle must be followed, that is, the order of values of the two must be the same, otherwise the data cannot be obtained correctly: when the position of start_index is to the left of end_index, it means that the value is taken from left to right, and step must be a positive number ( It also means from left to right); when the position of start_index is to the right of end_index, it means that the value is taken from right to left. At this time, step must be a negative number (it also means from right to left). For special cases, when start_index or end_index is omitted, the start index and end index are determined by the positive or negative of step. There will be no conflict in the direction of the value, but the results obtained by positive and negative are completely different, because a One to the left and one to the right.
(2) When using slicing, the positive and negative of step must be considered, especially when step is omitted. For example, a[-1:] can easily be mistaken as starting from the "end" to the "starting point", that is, a[-1:]= [0, 1, 2, 3, 4, 5, 6, 7 , 8, 9], but in fact a[-1:]=a[-1]=9, the reason is that step=1 means taking the value from left to right, and the starting index start_index=-1 itself is the highest value of the object. There are no elements on the right, and there is no data further to the right, so there is only one element a[-1].
The above is the detailed content of A thorough understanding of python slicing operations in one article. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
