Suppose we get an array using following code, what is the efficient way to get array[0], array[N], ..., array[MN-N]
to form a new array, and get array[1], array[N+1],..., array[MN-N+1]
to form another array, and ..., etc.
假设我们使用以下代码得到一个数组,有什么方法可以得到数组[0],数组[N],...,数组[MN-N]形成一个新数组,得到数组[1],数组[N + 1],...,数组[MN-N + 1]形成另一个数组,......等
array = []
for i in range(M):
for j in range(N):
array.append(something)
1 个解决方案
#1
1
With numpy
, you can use reshape
:
有了numpy,你可以使用reshape:
np.reshape(array, (M, N))
Then the columns are the arrays you are looking for.
然后列是您要查找的数组。
M = 3
N = 2
array = []
for i in range(M):
for j in range(N):
array.append(i+j)
array
# [0, 1, 1, 2, 2, 3]
np.reshape(array, (M, N))
# array([[0, 1],
# [1, 2],
# [2, 3]])
#1
1
With numpy
, you can use reshape
:
有了numpy,你可以使用reshape:
np.reshape(array, (M, N))
Then the columns are the arrays you are looking for.
然后列是您要查找的数组。
M = 3
N = 2
array = []
for i in range(M):
for j in range(N):
array.append(i+j)
array
# [0, 1, 1, 2, 2, 3]
np.reshape(array, (M, N))
# array([[0, 1],
# [1, 2],
# [2, 3]])