在numpy中生成nxn数组

时间:2017-04-24 06:47:04

标签: python-2.7 numpy

我可以像这样生成一个数组:

arr = np.array(range(0,36))
arr
#Output
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
   17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
   34, 35])

我的问题是如何生成nxn数组,如:

array([[ 0, 1, 2, 3, 4, 5],
[6,  7,  8,  9, 10, 11],
[12, 13, 14, 15, 16, 17], 
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]])

1 个答案:

答案 0 :(得分:0)

你写的输出看起来不正确的方法,如果你的意思是6x6阵列那么就是:

IMAGE

请注意,这里有一组外方括号,与您想要的输出相比......

稍微紧凑(>>> arr = np.array(range(0,36)).reshape((6,6)) >>> arr array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35]]) 可以采用多个args)并且可能更快(.reshape thx @jadsq):

np.arange