I found the following code that is compatible with python2
from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
However, this isn't working with Python 3. I get the following error
ImportError: cannot import name izip_longest
Can someone help?
I'd like to convert my list of [1,2,3,4,5,6,7,8,9]
to [[1,2,3],[4,5,6],[7,8,9]]
Edit
Now Python3 compatible
Code below is adapted from the selected answer. Simply change name from izip_longest
to zip_longest
.
from itertools import zip_longest
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)