Python 如何定义二维数组?
我想定义一个没有初始化长度的二维数组,如下所示:Python 如何定义二维数组?,python,matrix,syntax-error,Python,Matrix,Syntax Error,我想定义一个没有初始化长度的二维数组,如下所示: Matrix = [][] data=[] for l in infile: l = split(',') data.append(l) import numpy as np mm = np.matrix([]) mm = np.append(mm, [[1,2]], axis=1) 但它不起作用 我尝试了下面的代码,但它也是错误的: Matrix = [5][5] 错误: # 2D array/ matrix # 5
Matrix = [][]
data=[]
for l in infile:
l = split(',')
data.append(l)
import numpy as np
mm = np.matrix([])
mm = np.append(mm, [[1,2]], axis=1)
但它不起作用
我尝试了下面的代码,但它也是错误的:
Matrix = [5][5]
错误:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
我的错误是什么?从技术上讲,您试图为未初始化的数组编制索引。在添加项目之前,必须首先使用列表初始化外部列表;Python称之为 “列表理解” 现在可以将项目添加到列表中: 请注意,矩阵是“y”地址主键,换句话说,“y索引”位于“x索引”之前
尽管您可以随意命名它们,但我这样看是为了避免索引中可能出现的一些混乱,如果您对内部和外部列表都使用“x”,并且想要一个非方形矩阵。如果您想要创建一个空矩阵,正确的语法是
matrix = [[]]
如果你想生成一个大小为5,填充0的矩阵
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
您应该列出一个列表,最好的方法是使用嵌套理解:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
在您的[5][5]
示例中,您正在创建一个包含整数“5”的列表,并尝试访问其第5项,这自然会引发索引器,因为没有第5项:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>l=[5]
>>>l[5]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器:列表索引超出范围
在Python中,您将创建一个列表列表。您不必提前声明维度,但可以。例如:
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
现在矩阵[0][0]==2和矩阵[1][0]==3。您还可以使用列表理解语法。本例使用它两次构建“二维列表”:
来自itertools导入计数,takewhile
矩阵=[[i表示takewhile中的i(λj:j<(k+1)*10,计数(k*10))]表示范围(10)中的k]
如果你真的想要一个矩阵,最好使用numpy
。numpy
中的矩阵运算通常使用二维数组类型。创建新阵列的方法有很多;最有用的函数之一是zeros
函数,它接受一个形状参数并返回一个给定形状的数组,其值初始化为零:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
以下是创建二维阵列和矩阵的一些其他方法(为了紧凑性而删除输出):
numpy
也提供了一个矩阵
类型,但它可用于任何用途,将来可能会从numpy
中删除。以下是一个用于初始化列表的较短符号:
matrix = [[0]*5 for i in range(5)]
不幸的是,将其缩短为类似于5*[5*[0]]
的内容实际上不起作用,因为您最终会得到同一列表的5个副本,因此当您修改其中一个副本时,它们都会发生更改,例如:
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
我在逗号分隔的文件中读到如下内容:
Matrix = [][]
data=[]
for l in infile:
l = split(',')
data.append(l)
import numpy as np
mm = np.matrix([])
mm = np.append(mm, [[1,2]], axis=1)
然后,列表“数据”是一个列表,其中包含索引数据[row][col]以声明零(1)矩阵: e、 g 或 整数((x,y)) e、 g 甚至三维也是可能的。 (请参见-->多维数组)
请注意这个简短的表达式,请参见@F.J答案中的完整解释我正在编写我的第一个Python脚本,我对方形矩阵示例有点困惑,因此我希望下面的示例将帮助您节省一些时间:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
所以
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
如果您只需要一个二维容器来容纳某些元素,则可以方便地使用字典:
Matrix = {}
然后你可以做:
Matrix[1,2] = 15
print Matrix[1,2]
这是因为1,2
是一个元组,您将它用作索引字典的键。结果类似于哑稀疏矩阵
正如osa和Josap Valls所指出的,您还可以使用Matrix=collections.defaultdict(lambda:0)
,以便缺少的元素具有默认值0
Vatsal进一步指出,这种方法对于大型矩阵可能不是很有效,应该只用于代码的非性能关键部分。使用:
matrix = [[0]*5 for i in range(5)]
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
第一个维度的*5起作用,因为在这个级别上,数据是不可变的。使用:
matrix = [[0]*5 for i in range(5)]
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
我确实认为NumPy是一条路要走。如果您不想使用NumPy,以上是一个通用的方法。公认的答案是正确的,但我花了一段时间才明白,我也可以使用它创建一个完全空的数组
l = [[] for _ in range(3)]
导致
[[], [], []]
为便于阅读而重写:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
如果您希望能够将其视为2D数组,而不是被迫按照列表列表进行思考(我认为这更自然),您可以执行以下操作:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
结果是一个列表(不是NumPy数组),您可以用数字、字符串等覆盖各个位置。这就是字典的目的!
您可以通过两种方式定义键和值:
matrix[0,0] = value
或
结果:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
如果开始之前没有大小信息,请创建两个一维列表
list 1: To store rows
list 2: Actual two-dimensional matrix
将整行存储在第一个列表中。完成后,将列表1追加到列表2中:
from random import randint
coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=[]
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
输出:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
使用NumPy可以如下方式初始化空矩阵:
Matrix = [][]
data=[]
for l in infile:
l = split(',')
data.append(l)
import numpy as np
mm = np.matrix([])
mm = np.append(mm, [[1,2]], axis=1)
然后像这样附加数据:
Matrix = [][]
data=[]
for l in infile:
l = split(',')
data.append(l)
import numpy as np
mm = np.matrix([])
mm = np.append(mm, [[1,2]], axis=1)
使用列表:
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
通过使用dict:
您还可以将此信息存储在哈希表中,以便像
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
矩阵['1']将在O(1)时间内给出结果
*nb:您需要处理哈希表中的冲突这就是我通常在python中创建2D数组的方式
col = 3
row = 4
array = [[0] * col for _ in range(row)]
我发现与在列表理解中使用两个for循环相比,这种语法更容易记住
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)]
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
为什么这么长的代码,在Python
中也是如此
很久以前,当我对Python感到不舒服时,我看到了编写2D矩阵的单行答案,并告诉自己我不会再在Python中使用2D矩阵。(这一行非常吓人,它没有告诉我Python在做什么。还要注意的是,我不知道这些速记。)
不管怎样,这是一个初学者的代码
[[1], []]
Matrix[1].append(1)
[[], [1]]
# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))
# initialize the list
l=[[0]*cols for i in range(rows)]
# fill some random values in it
for i in range(0,rows):
for j in range(0,cols):
l[i][j] = i+j
# print the list
for i in range(0,rows):
print()
for j in range(0,cols):
print(l[i][j],end=" ")