问题
I'm trying to create a list that holds this exact format: [[2],[2],[2],[2],[2],[2],[2],[2],[2],[2]]
and when list[3][0] = 9 is called, the list becomes [[2],[9],[2],[9],[2],[9],[2],[9],[2],[9]]
How do I create the list in the first place that will allow me to change these many elements with only one line?
回答1:
>>> L = [[2], [2]] * 5
>>> L
[[2], [2], [2], [2], [2], [2], [2], [2], [2], [2]]
>>> L[3][0] = 9
>>> L
[[2], [9], [2], [9], [2], [9], [2], [9], [2], [9]]
This is because the same two lists are repeated over and over
>>> [id(x) for x in L]
[140053788793352, 140053788793288, 140053788793352, 140053788793288, 140053788793352, 140053788793288, 140053788793352, 140053788793288, 140053788793352, 140053788793288]
回答2:
Kindly check the output, as it should give
[[2], [2], [2], [9], [2], [2], [2], [2], [2], [2]]
as the output.
来源:https://stackoverflow.com/questions/42432230/how-to-create-a-2d-list-with-all-same-values-but-can-alter-multiple-elements-wit