如何创建具有所有相同值但可以更改其中的多个元素的二维列表?(Python) [英] How to create a 2d list with all same values but can alter multiple elements within? (python)

查看:56
本文介绍了如何创建具有所有相同值但可以更改其中的多个元素的二维列表?(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包含这种确切格式的列表:[[2],[2],[2],[2],[2],[2],[2],[2],[2],[2]]

list[3][0] = 9被调用时,列表变成[[2],[9],[2],[9],[2],[9],[2],[9],[2],[9]]

我首先如何创建列表,以便我只用一行更改这么多元素?

解决方案

>>>L = [[2], [2]] * 5>>>升[[2], [2], [2], [2], [2], [2], [2], [2], [2], [2]]>>>L[3][0] = 9>>>升[[2], [9], [2], [9], [2], [9], [2], [9], [2], [9]]

这是因为相同的两个列表一遍又一遍地重复

<预><代码>>>>[id(x) for x in L][140053788793352,140053788793288,140053788793352,140053788793288,140053788793352,140053788793288,140053788793352,140053788793288,140053788793352,140053788793288]

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?

解决方案

>>> 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]

这篇关于如何创建具有所有相同值但可以更改其中的多个元素的二维列表?(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆