# python获取二维数组 - 多维list

## 如何在Python中定义一个二维数组 (14)

``````Matrix = [][]
``````

``````Matrix = [5][5]
``````

``````Traceback ...

IndexError: list index out of range
``````

## 这就是字典是为了！

``````matrix = {}
``````

``````matrix[0,0] = value
``````

``````matrix = { (0,0)  : value }
``````

``````   [ value,  value,  value,  value,  value],
[ value,  value,  value,  value,  value],
...
``````

``````# 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)
``````

``````# 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)]
``````

# 您现在可以将项目添加到列表中：

``````Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid

print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
``````

``````>>> 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]]
``````

``````>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
``````

``````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
``````

``````matrix = [[0]*5 for i in range(5)]
``````

``````numpy.zeros((x, y))
``````

``````>>> numpy.zeros((3, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.]])
``````

``````>>> np.ones((3, 5))
array([[ 1.,  1.,  1.,  1.,  1.],
[ 1.,  1.,  1.,  1.,  1.],
[ 1.,  1.,  1.,  1.,  1.]])
``````

``````Matrix = {}
``````

``````Matrix[1,2] = 15
print Matrix[1,2]
``````

Vatsal进一步指出，这种方法对于大型矩阵可能不是非常有效，应该仅用于代码的非性能关键部分。

``````>>> 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`提供`matrix`类型。 它不常用，有些人建议不要使用它。 但对于来自Matlab以及其他一些环境的人来说，这是非常有用的。 因为我们在谈论矩阵，所以我想我会加入它！

``````>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
``````

``````numpy.matrix('1 2; 3 4')                 # use Matlab-style syntax
numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones
numpy.ndarray((5, 5))                    # use the low-level constructor
``````

``````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]]
``````

`````` # 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
``````

``````data=[]
for l in infile:
l = split(',')
data.append(l)
``````

``````matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
``````

``````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]};
``````

* nb ：你需要处理散列表中的冲突

``````# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
``````