How to create a 2d list with all same values but can alter multiple elements within? (python)

牧云@^-^@ 提交于 2019-12-25 18:17:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!