给出
list = [0,1,2,3,4,5,6,7,8,9,10]
如何获得如下的2D列表:
2dList = [[0,1,2,3],[2,3,4,5],[4,5,6,7],[6,7,8,9],[8,9,10]]
(“2dList”的每个第一维有4个值,“list”有2个值的“shift”。当没有4个值满足第一个维度时,它只存储“列表“]
谢谢!
答案 0 :(得分:2)
my_list = [0,1,2,3,4,5,6,7,8,9,10]
move_amount = 2
slice_size = 4
print [my_list[i:i + slice_size] for i in range(
0, len(my_list) - move_amount, move_amount)]
答案 1 :(得分:2)
如果您愿意使用numpy
,您可以更改阵列步幅以达到您想要的效果:
import numpy as np
from numpy.lib.stride_tricks import as_strided
a = np.array([0,1,2,3,4,5,6,7,8,9,10, 11]) # added 11 to avoid a memory mess
as_strided(a, shape=(5,4), strides=(a.strides[0]*2, a.strides[0]))
#array([[ 0, 1, 2, 3],
# [ 2, 3, 4, 5],
# [ 4, 5, 6, 7],
# [ 6, 7, 8, 9],
# [ 8, 9, 10, 11]])
并且在内存中这实际上就是数组a
中的内容,它可以用于某些目的......