Reputation: 88236
Say I have the following list:
l = [4,3,1,5,3,5,8,11,10,4,12,2,1]
What is the most pythonic way to slice l
in order to get chunks of length n
leaving k
items between chunks?
For example, if n=2
and k=3
the result should be:
[4,3,5,8,12,2]
Upvotes: 2
Views: 205
Reputation: 82
My take would be list comprehensions, even though you need to use two because otherwise it would just produce a list of lists.
l = [4,3,1,5,3,5,8,11,10,4,12,2,1]
n = 2
k = 3
chunk_l = [y for x in [l[i:i+n] for i in range(0,len(l), n+k)] for y in x]
print(chunk_l)
#[4, 3, 5, 8, 12, 2]
Upvotes: 1
Reputation: 39052
One alternate solution using slicing could be following
l = np.array([4,3,1,5,3,5,8,11,10,4,12,2,1])
A = l[:][::5]
B = l[1:][::5]
final = np.insert(B, np.arange(len(A)), A)
# array([ 4, 3, 5, 8, 12, 2])
l[:][::5]
gives you every 5th element starting from the first element and l[1:][::5]
gives you every 5th element starting from the second element. You then merge the two together
Upvotes: 0
Reputation: 109
A possible solution is
l = [4,3,1,5,3,5,8,11,10,4,12]
k,n=3,2
res=[]
while l:
res+=l[:n]
l=l[n+k:]
print(res)
This can be probably be heavily optimized in way of pythonicizity.
Upvotes: 0
Reputation: 214957
Use a list comprehension:
[e for i in range(0, len(l), n+k) for e in l[i:i+n]]
# [4, 3, 5, 8, 12, 2]
A numpy
solution would be:
import numpy as np
idx = (np.arange(0, len(l), n+k)[:,None] + np.arange(n)).ravel()
np.array(l)[idx]
# array([ 4, 3, 5, 8, 12, 2])
Upvotes: 5