Python two-dimensional array operations, python two-dimensional array operations
You need to use a two-dimensional array in the program. You can find this usage on the Internet:
| 123456 |
# Create an array with a width of 3 and a height of 4#[[0,0,0], # [0,0,0],# [0,0,0],# [0,0,0]]myList = [[0] * 3] * 4 |
However, when myList [0] [1] = 1, the entire second column is assigned a value and becomes
[[0, 1, 0],
[0, 1],
[0, 1],
[0, 1]
Why? I don't understand it for a moment. I will refer to The Python Standard Library to find The answer later.
List * n-> nShallow copiesOf list concatenated, n listsShortest copyConnection
Example:
| 123456 |
>>> lists = [[]] * 3>>> lists[[], [], []]>>> lists[0].append(3)>>> lists[[3], [3], [3]] |
[[] Is a list containing an empty list element. Therefore, [[] * 3 indicates three references pointing to this empty list element. modify any
An element changes the entire list:
Therefore, you need to create a multi-dimensional array in another way to avoid copying:
| 123456 |
>>> lists = [[] for i in range(3)]>>> lists[0].append(3)>>> lists[1].append(5)>>> lists[2].append(7)>>> lists[[3], [5], [7]] |
The previous two-dimensional array creation method is as follows:
| 1 |
myList = [([0] * 3) for i in range(4)] |