[英]Create a list of lists of lists in a single line
This code creates a list of 25 lists of 25 lists:此代码创建一个包含 25 个列表的 25 个列表的列表:
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?我如何将这段代码翻译成一行而不是在 Python 中使用 5 行?
You can use list_comprehension
.您可以使用
list_comprehension
。
res = [[[] for _ in range(25)] for _ in range(25)]
To check that result is the same, we can use numpy.ndarray.shape
.要检查结果是否相同,我们可以使用
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: numpy
的方式:
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
:您还可以使用基于
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.