4 ms·
From Itertools Recipes [6]: def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, '
by d0mine 13y ago
From Itertools Recipes [6]:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
- What is the most “pythonic” way to iterate over a list in chunks? [1]
- Idiomatic way to take groups of n items from a list in Python? [2]
- Python “Every Other Element” Idiom [3]
- Iterate an iterator by chunks (of n) in Python? [4]
- How do you split a list into evenly sized chunks in Python? [5]
[1]: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks http://stackoverflow.com/questions/434287/what-is-the-most-p...
[2]: http://stackoverflow.com/questions/2461484/idiomatic-way-to-take-groups-of-n-items-from-a-list-in-python http://stackoverflow.com/questions/2461484/idiomatic-way-to-...
[3]: http://stackoverflow.com/questions/2631189/python-every-other-element-idiom http://stackoverflow.com/questions/2631189/python-every-othe...
[4]: http://stackoverflow.com/questions/8991506/iterate-an-iterator-by-chunks-of-n-in-python http://stackoverflow.com/questions/8991506/iterate-an-iterat...
[5]: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python http://stackoverflow.com/questions/312443/how-do-you-split-a...
[6]: http://docs.python.org/3/library/itertools.html#itertools-recipes http://docs.python.org/3/library/itertools.html#itertools-re...
- iooi 13y agoFigured I would add my own [7]. I know the example prompt might seem a bit specific, but it can come in really handy sometimes (for example, iterating through get parameters). Always a fan of idiomatic and one-liner python. I should mention that I ended up using the fourth version (seemingly the slowest) but it is actually the fastest depending on your input -- as the length of the elements gets larger, the fourth method tends to vastly outperform the others. [7] http://stackoverflow.com/questions/16685545/elegantly-iterating-over-string-replacement http://stackoverflow.com/questions/16685545/elegantly-iterat...