Python slice day3

You can deal with some elements of the list --Python called slices.

First, use:

  To create a slice, you can specify the index of the first element to be used and the last element.

  Like the function range (), Python stops after it reached the front of the second index element.

  To output the first three elements of the list, specify an index from 0 to 3, which are output elements 0, 1 and 2.

The following is an example: 
L = [ ' Xiaoming ' , ' xiaohei ' , ' xiaobai ' , ' jaojun ' ] Print (L [0:. 1]) # slicing, care regardless of the end, does not contain elements behind Print (L [: 2]) # before the colon is not writing, from the foremost representative of zero Print (L [. 1:]) # after the colon do not write, from the rearmost end of the representative Print (L [:]) # is equivalent to print (l)

Second, the scope:

  Can be used as long as the index value of slice values ​​can be used; the: string, tuple list

= S ' ABCDEFG ' 
Print (S [:. 3]) # result is 'ABC' 
S2 = ' 1234567 ' 
Print (S2 [:: -. 1]) # slicing step, if negative, taken from the rear forward 7654321 
Print (S2 [-1: -5: -2]) # backwards taken, separated as a result of a value: 75

Third, the exercises for a list of memory addresses

# Entitled remove all odd 
Li = [1,1,2,3,4,5,6,7,8,9 ]
 # following method wrong way: 
for I in Li:
     IF ! I% 2 = 0 : 
        li.remove (I) 
Print (Li)
 # print result is [1, 2, 4, 6, 8] 
# reason: after removal of the first number, the index change, resulting in confusion subscript 
# cycles Do not delete the list when the inside of the element can lead to confusion subscript 
# solution: get two list, cycle li2, deletion of Li1 


# following method is the correct way: 
LI2 = [1,1,2,3,4,5, 6,7, 8,9 ]
 for I in LI2:
     IF I = 2%! 0: 
        li.remove (I) 
Print (Li) 


#Can not be written li2 = li; li is stored in the memory address from memory address to find the corresponding element; li2 corresponding to the same memory address, and li 
li2 = li # results li2 li and the same memory address 
Print ( " li memory address: " , ID (Li))
 Print ( " LI2 memory address: " , ID (LI2)) 
LI2 = Li [:] # microtome corresponds to generate a new list, different memory address 
Print ( " Li memory address: " , ID (Li ))
 Print ( " LI2 memory address: " , the above mentioned id (LI2))

 

Fourth, the shallow copy, deep copy

= L [12,3,4 ] 
L2 = L 
l.append ( ' 456 ' ) 
l2.remove ( 12 is )
 Print (L2) 

Import Copy 
stus = [ ' ABC ' , ' xiaohei ' , ' ABC2 ' ] 

stus1 = stus # shallow copy, the memory address has not changed 
stus2 stus = [:] # deep copy, change the memory address, independently of each other 
stus3 = copy.deepcopy (stus) # deep copy, copy modules need to introduce 


L1 = [ ' Xiaoming ' , 'xiaohei ' , ' xiaobai ' , ' jaojun ' , ' Xiaolei ' ]
 Print (L1 [0:. 6:. 1]) # one by one takes 
Print (L1 [0:. 6: 2]) # 2 in steps, every n-1 take a number

 

Guess you like

Origin www.cnblogs.com/candysalty/p/10974779.html