什么是用于创建具有一个固定维度大小和所有其他维度大小的 numpy 数组的 mory 优雅和 pythonic 解决方案?

What is a mory elegant and pythonic solution for creating a numpy array with one fixed dimension size and all others dynamic?

我有一个函数可以创建一个固定第一维的随机 numpy 数组。然而,所有其他的都可以动态改变。我写了一个非常简单的函数来完成这个,但是我预计这不是正确的方法,并且希望有一个更 pythonic 的解决方案。

def test(arg,first_dim=5):
    new_dims = []
    new_dims.append(first_dim)
    if type(arg) == int:
        new_dims.extend([arg])
    else:
        new_dims.extend(arg)
    return np.zeros(shape=new_dims) 

P.S.: 有人可能会争论将 5 直接放入 args,但是在我的具体情况下这是不可能的

你可以简单地做:

def test(arg,first_dim=5):
    return np.zeros(shape=[first_dim] + ([arg] if type(arg) is int else arg))

完全等同于你的代码。