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]]
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)
To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.
We define the chunkify function to split the lst list into n chunks. To do this, we use list comprehension to return slices of list with from index i to the end with n items in each chunk. Then we call chunkify with the list(range(13)) list and 3 to divide the list into 3 chunks.
The split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
In Python 3's itertools
there is a function called zip_longest
. It should do the same as izip_longest
from Python 2.
Why the change in name? You might also notice that itertools.izip
is now gone in Python 3 - that's because in Python 3, the zip
built-in function now returns an iterator, whereas in Python 2 it returns a list. Since there's no need for the izip
function, it also makes sense to rename the _longest
variant for consistency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With