简体   繁体   中英

How to create a multi-dimensional list

I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items.

Each list value should be initialized to the integer 0.

The obvious way to do this in a one-liner: myList = [[0]*10]*10 won't work because it produces a list of 10 references to one list, so changing an item in any row changes it in all rows.

The documentation I've seen talks about using [:] to copy a list, but that still won't work when using the multiplier: myList = [0]*10; myList = myList[:]*10 myList = [0]*10; myList = myList[:]*10 has the same effect as myList = [[0]*10]*10 .

Short of creating a loop of myList.append() s, is there a quick efficient way to initialize a list in this way?

您可以使用列表理解非常有效地做到这一点:

a = [[0] * number_cols for i in range(number_rows)]

这是...嵌套列表理解的工作

[[0 for i in range(10)] for j in range(10)]

Just thought I'd add an answer because the question asked for the general n-dimensional case and I don't think that was answered yet. You can do this recursively for any number of dimensions with the following example:

n_dims = [3, 4, 5]

empty_list = 0
for n in n_dims:
    empty_list = [empty_list] * n

>>>empty_list
>>>[[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]]

You might actually need an array instead of some lists. Almost every time I see this "presized nested list" pattern, something is not quite right.

An additional solution is to use NumPy library:

import numpy as np

zero_array = np.zeros((10, 10), dtype='int')

This can be easily converted to a regular python list with the .tolist() method if necessary.

I found that to get what you mean you need to youse

import copy

def n_dim_list(dims, init_val):
    if not dims:
        return []
    lst = [init_val for i in range(dims[-1])]
    for d in dims[::-1][1::]:
        lst = [copy.deepcopy(lst) for i in range(d)]
return lst

Where dims is a list of length of the number of the dimentions you want and the content is the size of the requiered nd-list in every dimention. Not the most elegant but clear and does the job.

Yet another method, but using the OP's rejected method.

import numpy as np
myList = [[0]*10]*10
myList = np.array(myList)
l=myList.tolist()
myList=l

The output and testing below:

>>> l
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
>>> l[0][0]=100
>>> l
[[100, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

The output is unlike the expected clone of l[0] .

Although this is not time efficient. It takes nearly 7 seconds for a 1000X1000 list, where as list comprehensions took only 0.0052158 seconds for the same.

Here is a function which works for an arbitrary number of dimensions using recursive list comprehensions. It doesn't need any imports to work.

def init_list(dims, val):
    if len(dims) == 0:
        raise ValueError("Requires at least 1 dimension.")

    if len(dims) == 1:
        return [val for _ in range(dims[0])]

    return [init_list(dims[1:], val=val) for _ in range(dims[0])]

Example:

>>> init_list([3, 2, 1], val=0)
[[[0], [0]], [[0], [0]], [[0], [0]]]

Two common and short way to do this:

First:

[[0] * n] * m

Second:

[[0 for column in range(n)] for row in range(m)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM