Python Beginner Tips: List

Keywords: Python list


C language and python are often confused, especially I can't help adding a semicolon after Python... Just make a note for myself to save forgetting... (from the little turtle)

7, List list

  1. The list contains multiple data types at the same time. The subscript index starts from 0. The subscript index value of the last element is - 1, and so on. The penultimate is - 2:
>>> word = [10,5,'you',0.1]
>>> for i in word:
	print(i)

10
5
you
0.1
>>> word[1]
5
>>> word[-2]
'you'
  1. The list slice prints the value corresponding to the subscript, excluding the last one
>>> word[1:3]  
[5, 'you']
>>> word[:2]  #There's no need to write your head in from the beginning
[10, 5]
>>> word[2:]  #There's no need to write the tail in until the end
['you', 0.1]
>>> word[:]
[10, 5, 'you', 0.1]
>>> word[0:4:2]  #Stride
[10, 'you']
>>> word[::2]  #Stride
[10, 'you']
>>> word[::-1]  #Reverse order output
[0.1, 'you', 5, 10]
  1. Addition, deletion, modification and query of list
    3.1 add
'''append And extend'''
>>> heros = ['Iron Man','The Incredible Hulk']
>>> heros.append('Black widow')  #Only one object can be added
>>> heros
['Iron Man', 'The Incredible Hulk', 'Black widow']
>>> heros.extend(['Eagle eye','Thanos ','Thor'])  #Add iteratable objects
>>> heros
['Iron Man', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Thanos ', 'Thor']

'''You can also use slicing to increase'''
>>> s = [1,'a',2,'d']
>>> s[len(s):] = [4,'add']
>>> s
[1, 'a', 2, 'd', 4, 'add']
>>> s[1:3] = [344,87]  #The original s[1:3] is replaced with a slice
>>> s
[1, 344, 87, 'd', 4, 'add']

'''At the specified location insert insert'''
>>> s.insert(1,'boy')  #Insert (position, element)
>>> s
[1, 'boy', 344, 87, 'd', 4, 'add']

3.2 delete

'''remove Delete specified element: if there are multiple matching elements in the list, only the first one will be deleted'''
>>> heros = ['Iron Man', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Thanos ', 'Thor']
>>> heros.remove('Thanos ')
>>> heros
['Iron Man', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Thor']

'''pop(subscript)Deletes the element at the specified location'''
>>> heros.pop(2)
'Black widow'
>>> heros
['Iron Man', 'The Incredible Hulk', 'Eagle eye', 'Thor']

'''clear()clear list '''
>>> heros.clear()
>>> heros
[]

3.3 modification

>>> heros = ['Iron Man', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Thanos ', 'Thor']
>>> heros[4] = 'Iron Man'
>>> heros
['Iron Man', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Iron Man', 'Thor']
>>> heros[3:] = ['Wu Song','Lin Chong','Li Kui']
>>> heros
['Iron Man', 'The Incredible Hulk', 'Black widow', 'Wu Song', 'Lin Chong', 'Li Kui']

'''sort()From small to large, sort(key=None, reverse=False),key Function used to specify a comparison, reverse Specifies whether the sort results are reversed'''
>>> num = [3,2,6,3,8,9,6,4,1,55]
>>> num.sort()
>>> num
[1, 2, 3, 3, 4, 6, 6, 8, 9, 55]

'''reverse()Sort from large to small'''
>>> num.reverse()
>>> num
[55, 9, 8, 6, 6, 4, 3, 3, 2, 1]
#However, if it is the initial num list, the result is as follows:
>>> num = [3,2,6,3,8,9,6,4,1,55]
>>> num.reverse()
>>> num
[55, 1, 4, 6, 9, 8, 3, 6, 2, 3]
#reverse() is actually an in-situ inversion function, which does not really sort from large to small, so the list containing strings can also use reverse:
>>> heros.reverse()
>>> heros
['Li Kui', 'Lin Chong', 'Wu Song', 'Black widow', 'The Incredible Hulk', 'Iron Man']

3.4 inspection

'''count()Find the number of times an element appears in the list (including numbers and strings)'''
>>> num = [3,2,6,3,8,9,6,4,1,55]
>>> num.count(3)  
2
>>> heros = ['Iron Man', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Iron Man', 'Thor']
>>> heros.count('Iron Man')   
2

'''index(x, start, end)Find element index value'''
>>> heros.index('Iron Man')
0  #If there are multiple elements, only the index value of the first element appears
>>> heros.index('The Incredible Hulk')
1
>>> heros[heros.index('Iron Man')] = 'Wonder woman'
>>> heros
['Wonder woman', 'The Incredible Hulk', 'Black widow', 'Eagle eye', 'Iron Man', 'Thor']
#By replacing elements with index values, when there are multiple elements, only the first one is operated
>>> num.index(3,1,20)  #It doesn't matter if end exceeds the length of the list
3

'''copy()Copy list'''
>>> num_copy1 = num.copy()
>>> num_copy1
[3, 2, 6, 3, 8, 9, 6, 4, 1, 55]
>>> num.pop(-1)
55
>>> num
[3, 2, 6, 3, 8, 9, 6, 4, 1]
>>> num_copy1
[3, 2, 6, 3, 8, 9, 6, 4, 1, 55]
>>> num_copy2 = num[:]
>>> num_copy2
[3, 2, 6, 3, 8, 9, 6, 4, 1]
>>> 
  1. Addition and multiplication of lists
>>> s = [1,2,3]
>>> t = [4,5,6]
>>> s + t  #Addition is splicing
[1, 2, 3, 4, 5, 6]
>>> s * 3  #Multiplication is repetition
[1, 2, 3, 1, 2, 3, 1, 2, 3]
  1. Nesting of lists
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix = [[1,2,3],
	      [4,5,6],
	      [7,8,9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

'''To access nested lists:'''
>>> for i in matrix:
			for j in i:
				print(j,end='')
			print()

123
456
789

>>> for i in matrix:
			for j in i:
				print(j,end=' ')  #If a space is added between the single quotation marks of end = '', there will be a space in the printed quotation marks
			print()
	
1 2 3 
4 5 6 
7 8 9 

>>> matrix[0]  #Subscript access nested list
[1, 2, 3]
>>> matrix[0][0]
1

>>> A = [0] * 4
>>> for i in range(2):
			A[i] = [1] * 2
	
>>> A
[[1, 1], [1, 1], 0, 0]
  1. python has different storage mechanisms for different objects:
>>> x = 'abc'
>>> y = 'abc'
>>> x is y
True   #Strings can be equal
>>> x = [1,2,3]
>>> y = [1,2,3]
>>> x is y
False  #Not the list

The assignment in python is not put into a box, but a reference. If we change the x above, y will also change; If you want two separate lists, you should use a copy.

  1. Copy is divided into shallow copy and deep copy:
'''Shallow copy is copy Or slice'''
#copy
>>> x = [1,2,3]
>>> y = x.copy()
>>> x[1] = 1
>>> x
[1, 1, 3]
>>> y
[1, 2, 3]
#section
>>> x = [1,2,3]
>>> y = x[:]
>>> x[1] = 1
>>> x
[1, 1, 3]
>>> y
[1, 2, 3]

However, shallow copies cannot work on nested lists:

>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> y = x.copy()
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]  

After copy, the content in x is changed, just like y, because shallow copy only copies the objects in the outer layer.
So use deep copy to solve this problem:

>>> import copy
>>> x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> y = copy.copy(x)  #The former copy represents the copy module, and the latter copy represents the copy function
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]  #Above or light copy

'''Deep copy deepcopy'''
>>> x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> y = copy.deepcopy(x)
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

However, it is more efficient to use shallow copies.

  1. List derivation: [expression for target in internal]

If you want to put the elements in the list × 2. How?

>>> x = [1,2,3,4,5]
>>> for i in range(len(x)):
	x[i] = x[i] * 2

	
>>> x
[2, 4, 6, 8, 10]

If a list derivation is used:

>>> x = [1,2,3,4,5]
>>> x = [i * 2 for i in x]
>>> x
[2, 4, 6, 8, 10]

Generally, the efficiency of list derivation is about twice as fast as that of loop statement: because list derivation is executed in C language in python, it is much faster than running for loop at a step-by-step speed in the virtual machine pym using python script.

8.1 list derivation: [expression for target in internal]

>>> x = [i for i in range(10)]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
#Replace i with i+1 to get 1 to 10

'''String isomorphism'''
>>> y = [i * 2 for i in 'nxy']
>>> y
['nn', 'xx', 'yy']

'''Convert characters to corresponding Unicode code'''
>>> code = [ord(i) for i in 'nxy']
>>> code
[110, 120, 121]

'''Extract elements of a column in a 2D list'''
>>> matrix = [[1,2,3],
	      [4,5,6],
	      [7,8,9]]
>>> col2 = [row[1] for row in matrix]  #Extract second column
#Each row in the matrix is extracted through the row statement, and row[1] is stored
>>> col2
[2, 5, 8]

'''Gets the main diagonal element'''
>>> diag = [matrix[i][i] for i in range(len(matrix))]  #Get i is 1, 2, 3
>>> diag
[1, 5, 9]
If it's a right diagonal?

Loop is to modify the elements in the original list through iteration, and the list derivation is to directly create a new list and assign it to the original variable name.
Create a nested list using a loop:

>>> for i in range(3):
	A[i] = [1] * 2
	
>>> A
[[1, 1], [1, 1], [1, 1]]
>>> A[0][1] = 0
>>> A
[[1, 0], [1, 1], [1, 1]]

Use list derivation to create a nested list:

>>> S = [[1] * 2 for i in range(3)]
>>> S
[[1, 1], [1, 1], [1, 1]]
>>> S[0][1] = 0
>>> S
[[1, 0], [1, 1], [1, 1]]

8.2 add if clause for filtering: [expression for target in internal if condition]

>>> even = [i for i in range(10) if i % 2 == 0]
>>> even
[0, 2, 4, 6, 8]
>>> even = [i + 1 for i in range(10) if i % 2 == 0]
>>> even
[1, 3, 5, 7, 9]  #Put all the above results + 1 → i+1
'''Execute first for Statement, and then execute if Statement, and finally the expression on the left'''

>>> word = ['agg', 'boy', 'cat', 'dog', 'apple', 'and']
>>> a_in = [i for i in word if 'a' in i]
>>> a_in
['agg', 'cat', 'apple', 'and']  #Words with a
>>> a_begin = [i for i in word if 'a' in i[0]]
>>> a_begin
['agg', 'apple', 'and']  #if 'a' == i[0]

8.3 list derivation can also be used to nest:
[expression for target1 in intrable1
for target2 in intrable2
......
for targetN in intrableN]
The nested outer loop is placed first.

>>> matrix = [[1,2,3], [4,5,6], [7,8,9]]
>>> fold = []
>>> for a in matrix:  #Take out the elements in the matrix, namely [1,2,3], [4,5,6], [7,8,9]
			for b in a:
				fold.append(b)
				print(fold)

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

8.4 finally developed ultimate Grammar:
[expression for target1 in intrable1 if condition1
for target2 in intrable2 if condition2
......
for targetN in intrableN if conditionN]**

>>> [[x,y] for x in range(6) if x % 2 == 0 for y in range(9) if y % 3 == 0]
[[0, 0], [0, 3], [0, 6], [2, 0], [2, 3], [2, 6], [4, 0], [4, 3], [4, 6]]

But you don't have to be too complicated to show off

Posted by IronicSoul on Sat, 23 Oct 2021 00:12:02 -0700