可能重复:
How do you split a list into evenly sized chunks in Python?
python: convert “5,4,2,4,1,0” into [[5, 4], [2, 4], [1, 0]]
[1,2,3,4,5,6,7,8,9]
- >
[[1,2,3],[4,5,6],[7,8,9]]
有没有简单的方法可以做到这一点,没有明确的'for'?
答案 0 :(得分:62)
>>> x = [1,2,3,4,5,6,7,8,9]
>>> zip(*[iter(x)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
答案 1 :(得分:15)
如果你真的希望子元素是列表与元组:
In [9]: [list(t) for t in zip(*[iter(range(1,10))]*3)]
Out[9]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
或者,如果要包含将被zip
截断的左侧元素,请使用切片语法:
In [16]: l=range(14)
In [17]: [l[i:i+3] for i in range(0,len(l),3)]
Out[17]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]
答案 2 :(得分:9)
您也可以在此使用numpy.reshape
:
import numpy as np
x = np.array([1,2,3,4,5,6,7,8,9])
new_x = np.reshape(x, (3,3))
结果:
>>> new_x
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
答案 3 :(得分:7)
>>> map(None,*[iter(s)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
答案 4 :(得分:0)
这是使用递归执行此操作的一种“聪明”方式:
from itertools import chain
def groupsof(n, xs):
if len(xs) < n:
return [xs]
else:
return chain([xs[0:n]], groupsof(n, xs[n:]))
print list(groupsof(3, [1,2,3,4,5,6,7,8,9,10,11,12,13]))