# [python]将列表分组成包含多个子列表的列表

## 第一种方法

```def group_iter(iterator, n=2):
""" Given an iterator, it returns sub-lists made of n items
(except the last that can have len < n)
inspired by http://countergram.com/python-group-iterator-list-function"""
accumulator = []
for item in iterator:
accumulator.append(item)
if len(accumulator) == n: # tested as fast as separate counter
yield accumulator
accumulator = [] # tested faster than accumulator[:] = []
# and tested as fast as re-using one list object
if len(accumulator) != 0:
yield accumulator
```

```>>> group_iter([1, 2, 3, 4, 5, 6], 3)
<generator object group_iter at 0x02A43418>
>>> list(group_iter([1, 2, 3, 4, 5, 6], 3))
[[1, 2, 3], [4, 5, 6]]
>>> list(group_iter([1, 2, 3, 4, 5, 6], 4))
[[1, 2, 3, 4], [5, 6]]
```

## 第二种方法：

```>>> original_list = [1, 2, 3, 4, 5, 6]
>>> list_size = 5
>>> [original_list[i:i+list_size] for i in xrange(0, len(original_list), list_size)]
[[1, 2, 3, 4, 5], [6]]
>>>
```

## 第三种方法：

```def splitarray(array, gsize):
arraylen = len(array)
for i in range(arraylen / gsize):
yield array[i * gsize:(i * gsize) + gsize]
if arraylen % gsize != 0:
yield array[-(arraylen % gsize):]
```

```>>> original_list = [1, 2, 3, 4, 5, 6]
>>> list_size = 5
>>> [original_list[i:i+list_size] for i in xrange(0, len(original_list), list_size)]
[[1, 2, 3, 4, 5], [6]]
>>>
```