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