How about slicing and zipping:
a = [i for i in range(13)]
print('a =',a)
offset = 1
step = 2
b = [(x,y) for x,y in zip(a[offset::step],a[offset+1::step])]
print('b =', b)
offset = 2
step = 3
c = [(x,y) for x,y in zip(a[offset::step],a[offset+1::step])]
print('c =',c)
gives
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
b = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]
c = [(2, 3), (5, 6), (8, 9), (11, 12)]
EDIT
To generalise the above to arbitrary N
and P
, you can use slices
for list indexing:
def list_segmenter(L, N, P):
"""small function to segment a list (L) into chunks of size N with step size P"""
slices = [slice(P+i-1,len(L),P) for i in range(N)]
lists = [L[s] for s in slices]
return list(zip(*lists))
a = [i for i in range(13)]
##testing:
print(list_segmenter(a,2,2))
print(list_segmenter(a,2,3))
print(list_segmenter(a,4,3))
and the output is:
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]
[(2, 3), (5, 6), (8, 9), (11, 12)]
[(2, 3, 4, 5), (5, 6, 7, 8), (8, 9, 10, 11)]