任意复杂度指定形状的 numpy 随机数

numpy random numpers in specified shape of any complexity

def shaperand(s):
    r = []
    for i in s:
        if type(i) in [list,tuple]:
            r.append(shaperand(i))
        else:
            r.append(np.random.rand())
    return r

所以,

shaperand([[1,2],[3,4,5],[6,7]])

结果:

[[0.27611814857329864, 0.6271028191307862], [0.6245245446787084, 0.743259931401167, 0.9061663248784034], [0.7236900927531255, 0.540622773908648]]

我没有看到执行此操作的函数。如果有的话会更快。有没有更好、更漂亮的写法?

如果您使用的是 NumPy 数组,则非常简单:

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
np.random.random(a.shape)

如果你有列表,你可以这样做:

import random

def shaperand(s):
    return [shaperand(e) if isinstance(e, list) else random.random() for e in s]