在python中创建2d矩阵 [英] Creating a 2d matrix in python
问题描述
我创建了一个6x5的2d数组,最初每个单元格中只有一个.然后,我读取一个文件,并在读取它们时将其替换为数据.我首先创建一个空数组,因为数据在我正在读取的文件中处于未定义的顺序.我的第一次尝试是这样做的:
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:
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.
是否有一个简单的内衬即可创建此空数组?我可以做一些for循环并建立它,但这对于python来说似乎是不必要的冗长.
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.
推荐答案
使用嵌套的理解列表:
x = [[None for _ in range(5)] for _ in range(6)]
这篇关于在python中创建2d矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!