Data type explanation - List
A list is a group of ordered data combinations, and the data in the list can be modified
Definition of list
- You can define []
- You can also use the list function to define
- When defining the elements in the list, you need to use commas to separate each element. [1,2,3,4]
- The elements in the list can be of any type and are usually used to store a collection of similar items
Basic operation of list
- List definition [], list()
- List addition: splicing
- List multiplication: repeat
- Subscript of list: obtain and update
- Addition of list elements: list name append()
- Deletion of list elements
- del list [subscript]
- The pop() function deletes (the last by default) and returns the deleted element
Slice in list
List [start index: end index: step value]
- List [start index:] = = > from the start index to the end of the list
- List [: end value] = = > from the beginning to before the specified end index
- List [start index: end index] = = > from the start index to the specified end index
- List [start index: end index: step value] = = > from the beginning of the specified index to the end before the specified index, the value is sliced according to the specified step
- List [:] or list [::] = = > slice of all list elements
- List [: - 1] = = > get the elements of the list upside down
Example:
varlist = ['Lau Andy','Xue You Zhang','Zhang Guorong','dawn','Guo Fucheng','Little Shenyang','Lennon ','Song Xiaobao','Zhao Si'] # From the beginning of the index to the end of the list res = varlist[2:] # ['Zhang Guorong', 'Liming', 'Guo Fucheng', 'Little Shenyang', 'Liu Neng', 'song Xiaobao', 'Zhao Si'] # From start to before the specified end index res = varlist[:2] # ['Andy Lau', 'Jacky Cheung'] # From start index to specified end index res = varlist[2:6] # ['Zhang Guorong', 'Liming', 'Guo Fucheng', 'Little Shenyang'] # From the beginning of the specified index to the end before the specified index, the value is sliced according to the specified steps res = varlist[2:6:2] # ['Zhang Guorong', 'Guo Fucheng'] # Slice of all list elements res = varlist[:] res = varlist[::] # Output the elements of the list upside down res = varlist[::-1] # Use slicing method to update and delete list data print(varlist) # It starts from the specified subscript and ends before the specified subscript, and is replaced with the corresponding data (container type data, which will be split into each element for assignment) # varlist[2:6] = ['a','b','c',1,2,3] # varlist[2:6:2] = ['a','b'] # It needs to correspond to the number of elements to be updated # Slice deletion # del varlist[2:6] del varlist[2:6:2]
List correlation function
varlist = ['Lau Andy','Xue You Zhang','Zhang Guorong','Xue You Zhang','dawn','Guo Fucheng','Little Shenyang','Lennon ','Song Xiaobao','Zhao Si'] # len() detects the length of the current list and the number of elements in the list res = len(varlist) # count() detects the number of occurrences of the specified element in the current list res = varlist.count('Xue You Zhang') # append() appends a new element to the end of the list, and the return value is None varlist.append('Chuange') # insert() can add a new element to the index position specified in the list, varlist.insert(20,'aa') # pop() can stack the elements at the specified index position and return the elements out of the stack res = varlist.pop() # By default, the last element in the list will be out of the stack res = varlist.pop(2) # The elements of the specified index will be out of the stack in the list varlist = [1,2,3,4,11,22,33,44,1,2,3,4] # remove() can specify the elements in the list to be deleted, and only the first one can be deleted. If it is not found, an error is reported res = varlist.remove(1) # index() can find the index position where the specified element first appears in the list # res = varlist.index(1) # res = varlist.index(1,5,20) # You can find the index position of an element within the specified index range # extend() receives the data of a container type and appends the elements in the container to the original list # varlist.extend('123') # s.clear() # Empty list contents # varlist.clear() # reverse() list flip varlist.reverse() # sort() sorts the list res = varlist.sort() # By default, elements are sorted from small to large res = varlist.sort(reverse=True) # Sort elements from large to small res = varlist.sort(key=abs) # You can pass a function to sort according to the processing results of the function
Deep copy and shallow copy
Shallow copy
After using the copy function, the multidimensional list or container in the new list uses the same address as the original list. That is, if one place is changed, both the old and new lists will be changed
# Shallow copy can only copy the current list, not multidimensional list elements in the list varlist = [1,2,3] # A simple copy can make a copy of the list newlist = varlist.copy() # The operation on the list of new copies is also independent del newlist[1] # print(varlist,id(varlist)) # print(newlist,id(newlist)) ''' [1, 2, 3] 4332224992 [1, 3] 4332227552 ''' # Multidimensional list varlist = [1,2,3,['a','b','c']] # Use the copy function to copy a multidimensional list newlist = varlist.copy() ''' print(newlist,id(newlist)) print(varlist,id(varlist)) [1, 2, 3, ['a', 'b', 'c']] 4361085408 [1, 2, 3, ['a', 'b', 'c']] 4361898496 ''' # If it is a copied list, the multidimensional list in the original list will be changed when operating on its multidimensional list elements del newlist[3][1] ''' adopt id After detection, it is found that the multidimensional list in the list is the same element (object) print(newlist[3],id(newlist[3])) print(varlist[3],id(varlist[3])) ['a', 'c'] 4325397360 ['a', 'c'] 4325397360 '''
Deep copy
Solve the problem of shallow copy and use the new address
Use the deep copy function in the copy module to complete the deep copy
# Deep copy not only copies the current list, but also copies the multidimensional elements in the list import copy varlist = [1,2,3,['a','b','c']] # Use the deep copy method deepcopy in the copy module newlist = copy.deepcopy(varlist) del newlist[3][1] print(varlist) print(newlist) ''' print(newlist[3],id(newlist[3])) print(varlist[3],id(varlist[3])) ['a', 'c'] 4483351248 ['a', 'b', 'c'] 4483003568 '''
List derivation
List-Comprehensions
List derivation provides a simpler way to create lists.
A common usage is to apply an operation to each element of a sequence or iteratable object, and then use its results to create a list, or to create a subsequence by satisfying certain conditional elements.
When an expression is used, the data is filtered or processed, and the results are formed into a new list
1, Basic list derivation usage
Result variable = [processing result of variable or variable for variable in container type data]
Example:
# Suppose we want to create a square list # Use common methods to complete varlist = [] for i in range(10): varlist.append(i**2) # print(varlist) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # This is done using the map function and list varlist = list(map(lambda x: x**2, range(10))) # print(varlist) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # Use the list push type to complete the following. The list push type is the same as the first method varlist = [i**2 for i in range(10)] # print(varlist) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # 2. '1234' ==> [2,4,6,8] # Conventional methods to complete requirements varstr = '1234' newlist = [] for i in varstr: newlist.append(int(i)*2) # print(newlist) # [2, 4, 6, 8] # Use list push to complete the above requirements newlist = [int(i)*2 for i in varstr] # print(newlist) # [2, 4, 6, 8] # Use the list push to + bit operation to complete newlist = [int(i) << 1 for i in varstr] # print(newlist) # [2, 4, 6, 8]
2, Push to list with judgment conditions
Result variable = [processing result of variable or variable for i in container type data condition expression]
Example:
# 0-9 find all even numbers, = = > [0, 2, 4, 6, 8] # Conventional method completion newlist = [] for i in range(10): if i % 2 == 0: newlist.append(i) # print(newlist) # [0, 2, 4, 6, 8] # List push to complete newlist = [i for i in range(10) if i % 2 == 0] # print(newlist) # [0, 2, 4, 6, 8]
3, For the list of nested loops, push to
''' # Here is a 3x4 matrix, which consists of three lists of length 4, exchanging their rows and columns [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] ==> [ [1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12] ] ''' arr = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] # Conventional method completion # newlist = [] # for i in range(4): # res = [] # for row in arr: # res.append(row[i]) # newlist.append(res) # print(newlist) # Use list push to complete newlist = [[row[i] for row in arr] for i in range(4)] print(newlist)
practice
#Row to column arr = [ [1,2,3,4], [5,6,7,8], [9,8,10,11,12], ] newlist = [[row[i] for row in arr] for i in range(4)]
#Use list derivation to complete the 99 multiplication table list = [[f'{x}×{y}={x*y}' for y in range(1,x+1)] for x in range(1,10)] print(list)
# Convert dictionary to list vardic = {'user':'admin','age':20,'phone':'123'} varlist=[f'{i}={vardic[i]}' for i in vardic] print(varlist)
# Converts all characters in the list to lowercase varlist = ['AAAAqA','bbbiubisAAAA','ccccccAAAAWQQE'] newlist=[i.lower() for i in varlist] print(newlist)
# x is an even number between 0-5 and y is an odd number between 0-5. Put x and y into a tuple in the list varlist = [(i,j) for j in range(5) if j % 2!= 0 for i in range(5) if i % 2 ==0] print(varlist)
# Realize 99 multiplication table in reverse order varlist = [[f'{i}×{j} = {i*j}' for j in range(1,i)] for i in range(9,0,-1)]