在python中创建一个二维矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4230000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a 2d matrix in python
提问by Colin
I create a 6x5 2d array, initially with just None in each cell. I then read a file and replace the Nones with data as I read them. I create the empty array first because the data is in an undefined order in the file I'm reading. My first attempt I did this:
我创建了一个 6x5 二维数组,最初每个单元格中只有 None 。然后我读取一个文件并在读取它们时用数据替换它们。我首先创建空数组,因为数据在我正在读取的文件中的顺序未定义。我第一次尝试这样做:
x = [[None]*5]*6
which resulted in some weird errors that I now understand is because the * operator on lists may create references instead of copies.
这导致了一些我现在理解的奇怪错误,因为列表上的 * 运算符可能会创建引用而不是副本。
Is there an easy one liner to create this empty array? I could just do some for loops and build it up, but that seems needlessly verbose for python.
是否有一个简单的衬里来创建这个空数组?我可以做一些 for 循环并构建它,但这对于 python 来说似乎是不必要的冗长。
采纳答案by Vincent Savard
Using nested comprehension lists :
使用嵌套理解列表:
x = [[None for _ in range(5)] for _ in range(6)]
回答by aaronasterling
What's going on here is that the line
这里发生的事情是这条线
x = [[None]*5]*6
expands out to
扩展到
x = [[None, None, None, None, None, None]]*6
At this point you have a list with 6 different references to the singleton None. You also have a list with a reference to the inner list as it's first and only entry. When you multiply it by 6, you are getting 5 more references to the inner list as you understand. But the point is that theres no problem with the inner list, just the outer one so there's no need to expand the construction of the inner lists out into a comprehension.
此时,您有一个列表,其中包含 6 个对单例的不同引用None。您还有一个包含对内部列表的引用的列表,因为它是第一个也是唯一的条目。当你将它乘以 6 时,你会得到 5 个对内部列表的引用,正如你所理解的。但关键是内部列表没有问题,只有外部列表,所以没有必要将内部列表的构造扩展为理解。
x = [[None]*5 for _ in range(6)]
This avoids duplicating references to any lists and is about as concise as it can readably get I believe.
这避免了对任何列表的重复引用,并且尽可能简洁,我相信它是可读的。
回答by Russell Borogove
If you aren't going the numpy route, you can fake 2D arrays with dictionaries:
如果你不走 numpy 路线,你可以用字典伪造二维数组:
>>> x = dict( ((i,j),None) for i in range(5) for j in range(6) )
>>> print x[3,4]
None

