Python multi-dimensional array initialization without a loop

前端 未结 12 1029
梦谈多话
梦谈多话 2020-12-13 22:26

Is there a way in Python to initialize a multi-dimensional array / list without using a loop?

12条回答
  •  余生分开走
    2020-12-13 23:01

    Python does not have arrays. It has other sequence types ranging from lists to dictionaries without forgetting sets - the right one depends on your specific needs.

    Assuming your "array" is actually a list, and "initialize" means allocate a list of lists of NxM elements, you can (pseudocode):

    • for N times: for M times: add an element
    • for N times: add a row of M elements
    • write the whole thing out

    You say you don't want to loop and that rules out the first two points, but why? You also say you don't want to write the thing down (in response to JacobM), so how would you exactly do that? I don't know of any other way of getting a data structure without either generating it in smaller pieces (looping) or explicitly writing it down - in any programming language.

    Also keep in mind that a initialized but empty list is no better than no list, unless you put data into it. And you don't need to initialize it before putting data...

    If this isn't a theoretical exercise, you're probably asking the wrong question. I suggest that you explain what do you need to do with that array.

提交回复
热议问题