Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hello,
I'm trying to find a simpler way to do the following:
def list_split(list, size):
result = [[]]
while len(list) > 0:
if len(result[-1]) >= size: result.append([])
result[-1].append(list.pop(0))
return result
Example usage:
>>> list_split([0, 1, 2, 3, 4, 5, 6], 2)
[[0, 1], [2, 3], [4, 5], [6]]
>>> list_split([0, 1, 2, 3, 4, 5, 6], 3)
[[0, 1, 2], [3, 4, 5], [6]]
I can't tell if there's a built-in way to do this, possibly with slicing or something.
This is similar but not the same to the post at How to split a list into a given number of sub-lists in python
Thanks
EDIT: As is commented on by Anurag Uniyal, this is a duplicate of How do you split a list into evenly sized chunks?, and should be closed, which I cannot do.
You could use slices to get subsets of a list.
Example:
>>> L = [0, 1, 2, 3, 4, 5, 6]
>>> n = 3
>>> [L[i:i+n] for i in range(0, len(L), n)]
[[0, 1, 2], [3, 4, 5], [6]]
>>>
You have a simple functional solution in the itertools recipes (grouper):
http://docs.python.org/library/itertools.html#recipes
Whereas this function adds padding, you can easily write a non-padded implementation taking advantage of the (usually overlooked) iter built-in used this way: iter(callable, sentinel) -> iterator
def grouper(n, it):
"grouper(3, 'ABCDEFG') --> ABC DEF G"
return iter(lambda: list(itertools.islice(it, n)), [])
list(grouper(3, iter(mylist)))
These solutions are more generic because they both work with sequences and iterables (even if they are infinite).
def list_split(L, size):
return [L[i*size:(i+1)*size] for i in range(1+((len(L)-1)//size))]
If you prefer a generator instead of a list, you can replace the brackets with parens, like so:
def list_split(L, size):
return (L[i*size:(i+1)*size] for i in range(1+((len(L)-1)//size)))
from itertools import izip_longest
def list_split(L, size):
return [[j for j in i if j is not None] for i in izip_longest(*[iter(L)]*size)]
>>> list_split([0, 1, 2, 3, 4, 5, 6], 2)
[[0, 1], [2, 3], [4, 5], [6]]
>>> list_split([0, 1, 2, 3, 4, 5, 6], 3)
[[0, 1, 2], [3, 4, 5], [6]]
>>> list_split([0, 1, 2, 3, 4, 5, 6], 4)
[[0, 1, 2, 3], [4, 5, 6]]
>>> list_split([0, 1, 2, 3, 4, 5, 6], 5)
[[0, 1, 2, 3, 4], [5, 6]]
精彩评论