Given a list eg. [2,3,4,10,20,30,102] I need all possible chunks/sublists of length 3 as follows,
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
Given a list eg. [2,3,4,10,20,30,102] I need all possible chunks/sublists of length 3 as follows,
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
This will do the job:
l= [2,3,4,10,20,30,102]
res=[l[i:i+3] for i in range(len(l)-2)]
print(res)
This prints
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
this function will do the work and more
def chunks(sequence, length):
sub_sequences = [sequence[offset:]
for offset in range(length)]
return zip(*sub_sequences)
for your example
list(chunks([2, 3, 4, 10, 20, 30, 102], length=3))
gives desired output
Use a list comprehension and a xrange operation will do you a favor.
Sample output
>>> a = [2,3,4,10,20,30,102]
>>> max_len = 3
>>> [ a[i-max_len: i] for i in xrange(max_len, len(a))]
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30]]
>>> max_len = 5
>>> [ a[i-max_len: i] for i in xrange(max_len, len(a))]
[[2, 3, 4, 10, 20], [3, 4, 10, 20, 30]]
arr = [2,3,4,10,20,30,102]
arr2 = arr
arr3 =[]
while (len(arr2) >= 3):
arr4=arr2[:3]
arr2 = arr2[1:]
arr3.append(arr4)
print("Original List \n")
print(arr)
print("\n")
print("List with all the chunks \n")
print(arr3)
The easiest way is to use slicing:
>>> s = [2, 3, 4, 10, 20, 30, 102]
>>> [s[i:i+3] for i in range(0, len(s)-2)]
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]