introduction
One 、Python Index method of slicable objects
Two 、Python The general way of slicing operation
3、 ... and 、Python Detailed example of slicing operation
1. Cut a single value
2. Cut the whole object
3.start_index and end_index It's all positive (+) Index
4.start_index and end_index It's all negative (-) Index
5.start_index and end_index just (+) negative (-) Mixed index
6. Continuous slice operation
7. The three parameters of slicing operation can be expressed as
8. Slicing of other objects
Four 、Python Commonly used slice operation
1. Take even position
2. Take the odd number position
3. Copy the entire object
4. Modify individual elements
5. Insert an element... In a certain location
6. Replace some elements
5、 ... and 、 summary
introductionUsing Python In the process of solving various practical problems , It is often encountered to extract part of the value from an object , Slicing operation is a powerful weapon specially used to complete this operation . Theoretically speaking , As long as the conditional expression is right , The target value can be arbitrarily cut by single or multiple slice operations . The basic syntax of slicing is relatively simple , But if we don't fully understand the inner logic , It's also very easy to make mistakes , And this kind of mistake is sometimes more hidden , Hard to detect . In this paper, we summarize and summarize the various situations of slicing operation through detailed examples . If there are any mistakes and shortcomings, please correct them !
One 、Python Index method of slicable objectsPython Index methods for slicable objects include : Positive index and negative index .
As shown in the figure below , With a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] For example :
Two 、Python The general way of slicing operationA complete slice expression contains two “:”, Used to separate three parameters (start_index、end_index、step), When there is only one “:” when , The third parameter is the default step=1.
Basic expression of slice operation :object[start_index : end_index : step]
step: Either positive or negative , Its absolute value determines the “ step ”, And the sign decides “ Cut the direction ”, It means “ From left to right ” Value , Negative representation “ From right to left ” Value . When step When omitted , The default is 1, That is, from left to right in increments 1 Value .“ Cutting direction is very important !”“ Cutting direction is very important !”“ Cutting direction is very important !”, Important things are to be repeated for 3 times !
start_index: Indicates the starting index ( Include the index itself ); When this parameter is omitted , To represent a subordinate “ Endpoint ” Start taking value , As for from “ The starting point ” Or from the “ End ” Start , By step The positive and negative determination of parameters ,step From “ The starting point ” Start , For the negative from “ End ” Start .
end_index: Indicates that the index is terminated ( Does not contain the index itself ); When this parameter is omitted , It means to fetch data all the way to ” Endpoint “, As for the arrival of ” The starting point “ Or to ” End “, By the same step The positive and negative determination of parameters ,step Set the timing until ” End “, It's negative until ” The starting point “.
3、 ... and 、Python Detailed example of slicing operationThe following examples are all in 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 the whole object >>> a[:] # From left to right [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> a[::] # From left to right [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> a[::-1] # From right to left [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
3.start_index and end_index It's all positive (+) Index >>> a[1:6] # step=1, From left to right ,start_index=1 To end_index=6 It also means to take the value from left to right .[1, 2, 3, 4, 5]>>>a[1:6:-1] # step=-1, Decided to take the value from right to left , and start_index=1 To end_index=6 Decided to take the value from left to right , The two contradict .>>> [] # The output is an empty list , It means that no data was obtained .>>>a[6:1] # step=1, Decided to take the value from left to right , and start_index=6 To end_index=1 Decided to take the value from right to left , The two contradict .>>> [] # The output is also an empty list .>>>a[:6] # step=1, From left to right , from “ The starting point ” Start taking it all the way to end_index=6.>>> [0, 1, 2, 3, 4, 5]>>>a[:6:-1] # step=-1, From right to left , from “ End ” Start taking it all the way to end_index=6.>>> [9, 8, 7]>>>a[6:] # step=1, From left to right , from start_index=6 Start , Take it all the way to “ End ”.>>> [6, 7, 8, 9]>>>a[6::-1] # step=-1, From right to left , from start_index=6 Start , Take it all the way to “ The starting point ”.>>> [6, 5, 4, 3, 2, 1, 0]
4.start_index and end_index It's all negative (-) Index >>>a[-1:-6] # step=1, From left to right , and start_index=-1 To end_index=-6 Decided to take the value from right to left , The two contradict .>>> []>>>a[-1:-6:-1] # step=-1, From right to left ,start_index=-1 To end_index=-6 It's also from right to left .>>> [9, 8, 7, 6, 5]>>>a[-6:-1] # step=1, From left to right , and start_index=-6 To end_index=-1 It's also from left to right .>>> [4, 5, 6, 7, 8]>>>a[:-6] # step=1, From left to right , from “ The starting point ” Start taking it all the way to end_index=-6.>>> [0, 1, 2, 3]>>>a[:-6:-1] # step=-1, From right to left , from “ End ” Start taking it all the way to end_index=-6.>>> [9, 8, 7, 6, 5]>>>a[-6:] # step=1, From left to right , from start_index=-6 Start , Take it all the way to “ End ”.>>> [4, 5, 6, 7, 8, 9]>>>a[-6::-1] # step=-1, From right to left , from start_index=-6 Start , Take it all the way to “ The starting point ”.>>> [4, 3, 2, 1, 0]
5.start_index and end_index just (+) negative (-) Mixed index >>>a[1:-6] # start_index=1 stay end_index=-6 Left side , So take the value from left to right , and step=1 It also determines the value from left to right .>>> [1, 2, 3]>>>a[1:-6:-1] # start_index=1 stay end_index=-6 Left side , So take the value from left to right , but step=- It determines the value from right to left , The two contradict .>>> []>>>a[-1:6] # start_index=-1 stay end_index=6 To the right of , So take the value from right to left , but step=1 Then it determines the value from left to right , The two contradict .>>> []>>>a[-1:6:-1] # start_index=-1 stay end_index=6 To the right of , So take the value from right to left , and step=-1 It also determines the value from right to left .>>> [9, 8, 7]
6. Continuous slice operation >>>a[:8][2:5][-1:]>>> [4]
amount 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, it can be used for infinite consecutive slice operations , As long as the last returned object is still a non empty slicable object .
7. The three parameters of slicing operation can be expressed as>>>a[2+1:3*2:7%3] # namely :a[2+1:3*2:7%3] = a[3:6:1]>>> [3, 4, 5]
8. Slicing of other objects The previous operation instructions for slicing are all in list Take an example to illustrate , But in fact, there are many types of data that can be sliced , Include tuples 、 Strings and so on .
>>> (0, 1, 2, 3, 4, 5)[:3] # Slice operation of tuples >>> (0, 1, 2)>>>'ABCDEFG'[::2] # String slicing operation >>>'ACEG'>>>for i in range(1,100)[2::3][-10:]: # utilize range Function generation 1-99 The integer of , And then take 3 Multiple , Take the last ten . print(i, end=' ')>>> 72 75 78 81 84 87 90 93 96 99
Four 、Python Commonly used slice operation To list :a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] To illustrate the object
1. Take even position>>>b = a[::2][0, 2, 4, 6, 8]
2. Take the odd number 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
It should be noted that :[:] and .copy() All belong to “ Shallow copy ”, Copy only the outermost elements , Inner nested elements are referenced by , Instead of allocating memory independently .
>>>a = [1,2,['A','B']]>>>print('a={}'.format(a))a=[1, 2, ['A', 'B']] # original a>>>b = a[:]>>>b[0] = 9 # modify b The outermost element , take 1 become 9>>>b[2][0] = 'D' # modify b The embedded layer elements of >>>print('a={}'.format(a)) # b Modify internal elements A by D after ,a Medium A Also became D, Explain sharing nested elements inside , But external elements 1 It hasn't changed .a=[1, 2, ['D', 'B']] >>>print('b={}'.format(b)) # The modified bb=[9, 2, ['D', 'B']] >>>print('id(a)={}'.format(id(a)))id(a)=38669128>>>print('id(b)={}'.format(id(b)))id(b)=38669192
4. Modify individual elements >>>a[3] = ['A','B'][0, 1, 2, ['A', 'B'], 4, 5, 6, 7, 8, 9]
5. Insert an element... In a certain location >>>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 some elements >>>a[3:6] = ['A','B'][0, 1, 2, 'A', 'B', 6, 7, 8, 9]
5、 ... and 、 summary ( One )start_index、end_index、step But it's all positive 、 Both are negative , It can also be mixed positive and negative . But there must be a principle , That is to say, the order of the two values must be the same , Otherwise, the data cannot be cut correctly : When start_index The position of is end_index On the left , Indicates the value from left to right , here step It must be a positive number ( It also means from left to right ); When start_index The position of is end_index On the right , Right to left , here step It has to be negative ( It also means from right to left ). For special cases , When start_index or end_index When omitted , The start index and the end index are created by step The positive and negative of , There will be no contradiction in the direction of value taking , But the positive and negative results are totally different , Because one to the left and one to the right .
( Two ) When using slices ,step The positive and negative of must be considered , Especially when step When omitted . such as a[-1:], It's easy to mistakenly think it's from “ End ” Start taking it all the way to “ The starting point ”, namely a[-1:]= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], But actually a[-1:]=a[-1]=9, The reason lies in step=1 Indicates the value from left to right , And the starting index start_index=-1 Itself is the rightmost element of the object , There's no more data to the right , So only a[-1] An element .
So far this article about an article has been thoroughly understood Python That's all for the slicing article , More about Python Please search the previous articles of SDN or continue to browse the related articles below. I hope you can support SDN more in the future !