简体   繁体   English

在python中创建一个2d矩阵

[英]Creating a 2d matrix in python

I create a 6x5 2d array, initially with just None in each cell. 我创建了一个6x5 2d阵列,最初在每个单元格中只有None。 I then read a file and replace the Nones with data as I read them. 然后,当我读取它时,我读取了一个文件并用数据替换了Nones。 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: 我第一次尝试这样做:

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来说这似乎是不必要的冗长。

使用嵌套的理解列表:

x = [[None for _ in range(5)] for _ in range(6)]

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 . 此时,您有一个列表,其中包含对单例None 6个不同引用。 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. 当你将它乘以6时,你会得到5个对内部列表的引用。 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. 但重点是内部列表没有问题,只有外部列表没有问题所以没有必要将内部列表的构建扩展为理解。

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. 这样可以避免重复对任何列表的引用,并且简洁,因为它可以让我相信。

If you aren't going the numpy route, you can fake 2D arrays with dictionaries: 如果你没有走numpy路线,你可以伪造带有字典的2D数组:

>>> x = dict( ((i,j),None) for i in range(5) for j in range(6) )
>>> print x[3,4]
None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM