是否有任何pythonic方法将列表拆分为范围为3的列表列表。
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [[1,2,3], [4,5,6], [7,8,9]]
prev,re= [],[]
for a in x:
if len(prev)==3:
re+=prev
prev=[]
else:
prev+=[a]
答案 0 :(得分:3)
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> n = 3
>>> [x[i:i+n] for i in range(0, len(x), n)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]