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

前端 未结 4 626
花落未央
花落未央 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:17

    Nothing wrong or un-Pythonic with

    dData = np.zeros(n)
    gData = np.zeros(n)
    etc.
    

    You could put them on one line, but there's no particular reason to do so.

    dData, gData = np.zeros(n), np.zeros(n)
    

    Don't try dData = gData = np.zeros(n), because a change to dData changes gData (they point to the same object). For the same reason you usually don't want to use x = y = [].

    The deal in MATLAB is a convenience, but isn't magical. Here's how Octave implements it

    function [varargout] = deal (varargin)
      if (nargin == 0)
        print_usage ();
      elseif (nargin == 1 || nargin == nargout)
        varargout(1:nargout) = varargin;
      else
        error ("deal: nargin > 1 and nargin != nargout");
      endif
    
    endfunction
    

    In contrast to Python, in Octave (and presumably MATLAB)

    one=two=three=zeros(1,3)
    

    assigns different objects to the 3 variables.

    Notice also how MATLAB talks about deal as a way of assigning contents of cells and structure arrays. http://www.mathworks.com/company/newsletters/articles/whats-the-big-deal.html

提交回复
热议问题