Issue
Let's say I have a list [1,2,3,4,5,6]
, and I want to iterate over all the subgroups of len 2 [1,2] [3,4] [5,6]
.
The naive way of doing it
L = [1,2,3,4,5,6]
N = len(L)//2
for k in range(N):
slice = L[k*2:(k+1)*2]
for val in slice:
#Do things with the slice
However I was wondering if there is a more pythonic method to iterate over a "partitioned" list already. I also accept solutions with numpy arrays
. Something like:
L = [1,2,3,4,5,6]
slices = f(L,2) # A nice "f" here?
for slice in slices:
for val in slice:
#Do things with the slice
Thanks a lot!
Solution
Use the grouper
recipe from the itertools
library:
import itertools
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 itertools.zip_longest(*args, fillvalue=fillvalue)
L = [1,2,3,4,5,6]
for slice in grouper(L, 2):
print(slice)
Answered By - Woodford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.