Initialize Multiple Numpy Arrays (Multiple Assignment) - Like MATLAB deal()

前端 未结 4 623
花落未央
花落未央 2020-12-14 23:32

I was unable to find anything describing how to do this, which leads to be believe I\'m not doing this in the proper idiomatic Python way. Advice on the \'proper\' Python w

4条回答
  •  無奈伤痛
    2020-12-15 00:18

    If you're really motivated to do this in a one-liner you could create an (n_vars, ...) array of zeros, then unpack it along the first dimension:

    a, b, c = np.zeros((3, 5))
    print(a is b)
    # False
    

    Another option is to use a list comprehension or a generator expression:

    a, b, c = [np.zeros(5) for _ in range(3)]   # list comprehension
    d, e, f = (np.zeros(5) for _ in range(3))   # generator expression
    print(a is b, d is e)
    # False False
    

    Be careful, though! You might think that using the * operator on a list or tuple containing your call to np.zeros() would achieve the same thing, but it doesn't:

    h, i, j = (np.zeros(5),) * 3
    print(h is i)
    # True
    

    This is because the expression inside the tuple gets evaluated first. np.zeros(5) therefore only gets called once, and each element in the repeated tuple ends up being a reference to the same array. This is the same reason why you can't just use a = b = c = np.zeros(5).

    Unless you really need to assign a large number of empty array variables and you really care deeply about making your code compact (!), I would recommend initialising them on separate lines for readability.

提交回复
热议问题