Home > Software design >  Splitting an array into sequential groups
Splitting an array into sequential groups

Time:02-12

I have an array with elements [2, 3, 4, 5, 6, 7, 8, 9, 10, ...]. I wish to split this up as follows: [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], ...]. I am not sure how to do this because the elements in each split must be repeated and I am unsure of how to create these repeated elements. Any help will be much appreciated.

CodePudding user response:

You can use zip() to create 3-tuples, and then use list() to transform the resulting tuples into lists.

data = [2, 3, 4, 5, 6, 7, 8, 9, 10]

# Prints [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]
print(list(list(item) for item in zip(data, data[1:], data[2:])))

CodePudding user response:

Use a comprehension:

N = 3
l = [2, 3, 4, 5, 6, 7, 8, 9, 10]

ll = [l[i:i N] for i in range(len(l)-N 1)]

Output:

>>> ll
[[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]

CodePudding user response:

The zip idea generalised for varying chunk size:

lst = [2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(zip(*(lst[i:] for i in range(3))))

CodePudding user response:

zip() and comprehension, suggested above, are probably the ways to go in "real life", but in order to better understand the problem, consider this very simple approach:

data = [2, 3, 4, 5, 6, 7, 8, 9, 10]

result = []

for i in range(0,len(data)-2):
    result.append([data[i],data[i 1],data[i 2]])

print(result) 

CodePudding user response:

There's a module "more_itertools" that has method that creates triples from a list:

import more_itertools
out = list(more_itertools.triplewise(lst))

Output:

[(2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

It's not a built-in module, so you'll have to install it (pip or conda or whatever you use) beforehand however.

  • Related