This article mainly introduces “python How to solve the initialization problem of one-dimensional and two-dimensional lists ” Knowledge about , Xiaobian shows you the operation process through practical cases , The operation method is simple and fast , Practical , Hope this article “python How to solve the initialization problem of one-dimensional and two-dimensional lists ” The article can help you solve problems .
The initial length is 5 A list of
The way 1:
a = [0]*5# [0, 0, 0, 0, 0]
The way 2:
a = [0 for _ in range(5)]# [0, 0, 0, 0, 0]
The first one 2*5 A list of :
The way 1:
b = [[0]*5 for _ in range(2)]# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
The way 2:
b = [[0 for _ in range(5)] for _ in range(2)]# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Be careful :
The following is wrong , This is equivalent to taking [0]*5 This one-dimensional list duplicates 2 Time , Whenever you change an element in one of the one-dimensional lists , The elements in the rest of the list will also change .
b = [[0]*5]*2# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] b[0][1] = 3 # [[0, 3, 0, 0, 0], [0, 3, 0, 0, 0]]
About “python How to solve the initialization problem of one-dimensional and two-dimensional lists ” That's all for , Thanks for reading . If you want to know more about the industry , You can pay attention to the Yisu cloud industry information channel , Xiaobian will update different knowledge points for you every day .