收录日期:2020/12/05 23:07:04 时间:2010-09-07 20:30:40 标签:python

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

Sure there is a way

arr = eval(`[[0]*5]*10`)

or

arr = eval(("[[0]*5]+"*10)[:-1])

but it's horrible and wasteful, so everyone uses loops (usually list comprehensions) or numpy

Depending on your real needs, the de facto "standard" package Numpy might provide you with exactly what you need.

You can for instance create a multi-dimensional array with

numpy.empty((10, 4, 100))  # 3D array

(initialized with arbitrary values) or create the same arrays with zeros everywhere with

numpy.zeros((10, 4, 100))

Numpy is very fast, for array operations.

Sure, you can just do

mylist = [
            [1,2,3],
            [4,5,6],
            [7,8,9]
         ]

I don't believe it's possible.

You can do something like this:

>>> a = [[0] * 5] * 5

to create a 5x5 matrix, but it is repeated objects (which you don't want). For example:

>>> a[1][2] = 1
[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]

You almost certainly need to use some kind of loop as in:

[[0 for y in range(5)] for x in range(5)]

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)

It depends on what you what to initialize the array to, but sure. You can use a list comprehension to create a 5×3 array, for instance:

>>> [[0 for x in range(3)] for y in range(5)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> [[3*y+x for x in range(3)] for y in range(5)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]

Yes, I suppose this still has loops—but it's all done in one line, which I presume is the intended meaning of your question?

If you're doing numerical work using Numpy, something like

x = numpy.zeros ((m,n))
x = numpy.ones ((m,n))

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.

a = [[]]
a.append([1,2])
a.append([2,3])

Then

>>> a
[[1, 2], [2, 3]]

The following does not use any special library, nor eval:

arr = [[0]*5 for x in range(6)]

and it doesn't create duplicated references:

>>> arr[1][1] = 2
>>> arr
[[0, 0, 0, 0, 0],
 [0, 2, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

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