使用
numpy.repeat
具有
np.arange
:
import numpy as np
arr = np.array([[[3, 1, 3, 1, 2],
[4, 4, 4, 2, 0],
[3, 4, 4, 4, 0],
[1, 4, 3, 3, 0]],
[[4, 2, 0, 2, 1],
[2, 1, 2, 0, 3],
[4, 1, 3, 4, 3],
[2, 3, 2, 0, 0]]])
arr2d = np.vstack(arr)
dup = arr2d[np.repeat(np.arange(arr2d.shape[0]), arr2d[:,0])]
np.split(dup, np.cumsum(np.sum(np.split(arr2d[:,0], arr.shape[0]), 1)))[:-1]
输出:
[array([[3, 1, 3, 1, 2],
[3, 1, 3, 1, 2],
[3, 1, 3, 1, 2],
[4, 4, 4, 2, 0],
[4, 4, 4, 2, 0],
[4, 4, 4, 2, 0],
[4, 4, 4, 2, 0],
[3, 4, 4, 4, 0],
[3, 4, 4, 4, 0],
[3, 4, 4, 4, 0],
[1, 4, 3, 3, 0]]),
array([[4, 2, 0, 2, 1],
[4, 2, 0, 2, 1],
[4, 2, 0, 2, 1],
[4, 2, 0, 2, 1],
[2, 1, 2, 0, 3],
[2, 1, 2, 0, 3],
[4, 1, 3, 4, 3],
[4, 1, 3, 4, 3],
[4, 1, 3, 4, 3],
[4, 1, 3, 4, 3],
[2, 3, 2, 0, 0],
[2, 3, 2, 0, 0]])]
由于2d数组并不总是具有相同的形状,因此在大多数情况下,它将生成数组列表。这样的不一致并没有得到很好的处理
numpy
.
在这种情况下,您可以简单地使用
itertools.repeat
具有
list
理解力。(尽管它看起来与@gmds的答案非常相似)
鉴于
l
:
import itertools
l = [[[3, 1, 3, 1, 2], [4, 4, 4, 2, 0], [3, 4, 4, 4, 0], [1, 4, 3, 3, 0]],
[[4, 2, 0, 2, 1], [2, 1, 2, 0, 3], [4, 1, 3, 4, 3], [2, 3, 2, 0, 0]]]
[[j for i in sub for j in itertools.repeat(i, i[0])] for sub in l]
输出:
[[[3, 1, 3, 1, 2],
[3, 1, 3, 1, 2],
[3, 1, 3, 1, 2],
[4, 4, 4, 2, 0],
[4, 4, 4, 2, 0],
[4, 4, 4, 2, 0],
[4, 4, 4, 2, 0],
[3, 4, 4, 4, 0],
[3, 4, 4, 4, 0],
[3, 4, 4, 4, 0],
[1, 4, 3, 3, 0]],
[[4, 2, 0, 2, 1],
[4, 2, 0, 2, 1],
[4, 2, 0, 2, 1],
[4, 2, 0, 2, 1],
[2, 1, 2, 0, 3],
[2, 1, 2, 0, 3],
[4, 1, 3, 4, 3],
[4, 1, 3, 4, 3],
[4, 1, 3, 4, 3],
[4, 1, 3, 4, 3],
[2, 3, 2, 0, 0],
[2, 3, 2, 0, 0]]]