Python - 多行数组

Max*_*rai 5 python arrays

在c ++我写道:

int someArray[8][8];
for (int i=0; i < 7; i++)
   for (int j=0; j < 7; j++)
      someArray[i][j] = 0;
Run Code Online (Sandbox Code Playgroud)

如何在python中初始化多行数组?我试过了:

array = [[],[]]
for i in xrange(8):
   for j in xrange(8):
        array[i][j] = 0
Run Code Online (Sandbox Code Playgroud)

YOU*_*YOU 7

>>> [[0]*8 for x in xrange(8)]
[[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, 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, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>>
Run Code Online (Sandbox Code Playgroud)


Ofr*_*viv 7

您询问了有关初始化列表的信息.它是一个非常有用的数据结构,但它与C++中的2D数组有一个重要的区别:不能保证所有行都具有相同的长度(即len(a[0])==len(a[1])(在C++中你确实有这种保证).

所以另一个可能很方便的解决方案是使用NumPy数组数据类型,如下所示:

import numpy as np
array = np.zeros((8,8))
Run Code Online (Sandbox Code Playgroud)

  • 很高兴知道numpy方式!+1 (2认同)