在python中,实现多维数组或矩阵,有两种常用方法:
内置列表方法和numpy 科学计算包方法。
下面以创建10*10矩阵或多维数组为例,并初始化为0,程序如下:
# Method 1: list arr1 = [[0]*10 for i in range(10)]arr1[0][0] = 1print "Method 1:\n", arr1arr2 = [[0 for i in range(10)] for i in range(10)]arr2[0][0] = 1print arr2# Wrong simplified versiona = [[0]*10]*10a[0][0] = 23print "Error Method:\n", a# Method 2: numpy packageimport numpy as nparr3 = np.array([[0]*10]*10)arr3[0][0] = 2print "Method 2:\n", arr3