Home >Backend Development >Python Tutorial >A thorough understanding of python slicing operations in one article

A thorough understanding of python slicing operations in one article

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼forward
2019-07-31 15:59:239004browse

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:

A thorough understanding of python slicing operations in one article

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more