Python multi-dimensional array initialization without a loop

前端 未结 12 998
梦谈多话
梦谈多话 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.

    0 讨论(0)
  • 2020-12-13 23:04

    You can do by this way:

    First without using any loop:

    [[0] * n] * m
    

    Secondly using simple inline list comprehension:

    [[0 for column in range(n)] for row in range(m)]
    
    0 讨论(0)
  • 2020-12-13 23:07

    Sure, you can just do

    mylist = [
                [1,2,3],
                [4,5,6],
                [7,8,9]
             ]
    
    0 讨论(0)
  • 2020-12-13 23:08
    a = [[]]
    a.append([1,2])
    a.append([2,3])
    

    Then

    >>> a
    [[1, 2], [2, 3]]
    
    0 讨论(0)
  • 2020-12-13 23:15

    Recursion is your friend :D

    It's a pretty naive implementation but it works!

    dim = [2, 2, 2]
    
    def get_array(level, dimension):
        if( level != len(dimension) ):
            return [get_array(level+1, dimension) for i in range(dimension[level])]
        else:
            return 0
    
    print get_array(0, dim)
    
    0 讨论(0)
  • 2020-12-13 23:17

    You can use N-dimensional array (ndarray). Here is the link to the documentation. http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html

    0 讨论(0)
提交回复
热议问题