在python中制作没有引用的列表列表 [英] Making a list of lists with no refrences in python

查看:94
本文介绍了在python中制作没有引用的列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以单行有效的方式列出列表,但是我无法提出任何避免引用的方法.到目前为止,这是我尝试过的,显然没有成功:

I am trying to make a list of lists in a one-lined efficient manner, but I can't come up with any way to avoid having references. This is what I have tried so far, obviously unsuccessfully:

>>> test=[[None]*3][:]*3
>>> test
[[None, None, None], [None, None, None], [None, None, None]]
>>> test[0][0]=0
>>> test
[[0, None, None], [0, None, None], [0, None, None]]
>>> 

这不是我想要发生的事情.我想要的是让0成为仅第一个列表的第一项.我该怎么办?

This is not what I want to happen. What I want is for 0 to be the first item of only the first list. How can I do this?

推荐答案

使用列表理解:

test = [[None] * 3 for _ in range(3)]

(请注意,_只是与输出无关的约定,在本例中为012)

(Note the _ is just a convention for output that is irrelevant, in this case 0, 1, and 2)

这篇关于在python中制作没有引用的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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