简体   繁体   中英

Create a list of lists of lists in a single line

This code creates a list of 25 lists of 25 lists:

vals = []
for i in range(25):
    vals.append([])
    for j in range(25):
        vals[i].append([])

How could I translate this code to a single line instead of using 5 lines in Python?

You can use list_comprehension .

res = [[[] for _ in range(25)] for _ in range(25)]

To check that result is the same, we can use numpy.ndarray.shape .

>>> import numpy as np
>>> np.asarray(vals).shape
(25, 25, 0)

>>> np.asarray(res).shape
(25, 25, 0)

Using list comprehension:

vals = [[[] for _ in range(25)] for _ in range(25)]

numpy way:

import numpy as np

vals = np.zeros((25,25,0)).tolist()

Just a fun hack for lazy people:

vals = eval(repr([[[]] * 25] * 25))

You can also use this approach based on map :

vals = list(map(lambda _: list(map(lambda __: [], range(25))), range(25)))

Fix size grouping from a flat list

n = 25
n_rows, n_cols = n, n

vals = [[[] for _ in range(n_rows*n_cols)][n_cols*i:(i+1)*n_cols] for i in range(n_rows)]

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