如何将python列表分成大小相等的块?

How to split python list into chunks of equal size?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
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
[1,2,3,4,5,6,7,8,9]

>

1
[[1,2,3],[4,5,6],[7,8,9]]

有没有简单的方法可以做到,没有明确的"for"?


1
2
3
>>> x = [1,2,3,4,5,6,7,8,9]
>>> zip(*[iter(x)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

zip(*[iter(s)]*n)如何在Python中工作?


如果您真的希望子元素是列表与元组:

1
2
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截断的剩余元素,请使用slice语法:

1
2
3
4
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]]


您也可以在这里使用numpy.reshape

1
2
3
4
5
import numpy as np

x = np.array([1,2,3,4,5,6,7,8,9])

new_x = np.reshape(x, (3,3))

结果:

1
2
3
4
>>> new_x
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


1
2
>>> map(None,*[iter(s)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]


下面是一种不太"聪明"的递归方法:

1
2
3
4
5
6
7
8
9
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]))