如何将列表重塑为 n 维列表
输入:列表 =[1, 2, 3, 4, 5, 6, 7, 8]
形状 =[2, 2, 2]
输出 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
小智 7
oooold post..但由于我目前正在寻找一种比我的更优雅的方式,我只是告诉你我的方法
# first, i create some data
l = [ i for i in range(256) ]
# now I reshape in to slices of 4 items
x = [ l[x:x+4] for x in range(0, len(l), 4) ]
Run Code Online (Sandbox Code Playgroud)
这种递归方法应该有效。
lst = [1, 2, 3, 4, 5, 6, 7, 8]
shape = [2, 2, 2]
from functools import reduce
from operator import mul
def reshape(lst, shape):
if len(shape) == 1:
return lst
n = reduce(mul, shape[1:])
return [reshape(lst[i*n:(i+1)*n], shape[1:]) for i in range(len(lst)//n)]
reshape(lst, shape)
Run Code Online (Sandbox Code Playgroud)
您可能想通过检查您的尺寸是否有意义来包装它......例如
assert reduce(mul, shape) == len(lst)
Run Code Online (Sandbox Code Playgroud)
这是一种在除第一个维度之外的每个维度上使用一次石斑鱼的方法:
import functools as ft
# example
L = list(range(2*3*4))
S = 2,3,4
# if tuples are acceptable
tuple(ft.reduce(lambda x, y: zip(*y*(x,)), (iter(L), *S[:0:-1])))
# (((0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)), ((12, 13, 14, 15), (16, 17, 18, 19), (20, 21, 22, 23)))
# if it must be lists
list(ft.reduce(lambda x, y: map(list, zip(*y*(x,))), (iter(L), *S[:0:-1])))
# [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6954 次 |
最近记录: |