Home > Enterprise >  Create a list of lists of lists in a single line
Create a list of lists of lists in a single line

Time:12-24

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?

CodePudding user response:

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)

CodePudding user response:

Using list comprehension:

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

CodePudding user response:

numpy way:

import numpy as np

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

CodePudding user response:

Just a fun hack for lazy people:

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

CodePudding user response:

You can also use this approach based on map:

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

CodePudding user response:

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)]
  • Related