Home > database >  Split array into multiple small arrays by moving start index by each time
Split array into multiple small arrays by moving start index by each time

Time:04-29

How to derive multiple small arrays from a large array by shifting array start position by one each time?

Example input array

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

Output: Multiple subarrays of size 3, starting at i=0,1,2,3.....

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

I can do this by writing my own code

split(input){
 i =0
 results = []
 while(i<len(input)-3):
   start = i
   end = i  3 
   subarray = input[start:end]
   results.append(subarray)
} 
 return results

Is there a python inbuilt function for this, or sum lib?

CodePudding user response:

Not in the standard library, but this is a great package: using more_itertools.windowed:

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

# pip install more-itertools
from more_itertools import windowed
list(windowed(l, 3))

output:

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

Or with numpy:

from numpy.lib.stride_tricks import sliding_window_view
sliding_window_view(l, 3).tolist()

output:

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

CodePudding user response:

Try with zip:

l = [1,2,3,4,5,6,7,8,9,10]
sublists = [list(zip(l,l[1:],l[2:]))]

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

CodePudding user response:

You can do this with list comprehension and indexing like so:

k = 3
r = [1,2,3,4,5,6,7,8,9,10]
r_sublists = [r[i:i k] for i in range(len(r) - k   1)]

Where k is the number of items in each sub-list.

CodePudding user response:

Here's how you can do it with list comprehension:

l = [1,2,3,4,5,6,7,8,9,10]
n = 3 # No of elements in each list
list_of_l = [l[i:i 3] for i in range(len(l)-n 1)]
list_of_l
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]

CodePudding user response:

You can do this just by NumPy as:

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9,10])
np.lib.stride_tricks.sliding_window_view(a, 3)

# [[ 1  2  3]
#  [ 2  3  4]
#  [ 3  4  5]
#  [ 4  5  6]
#  [ 5  6  7]
#  [ 6  7  8]
#  [ 7  8  9]
#  [ 8  9 10]]
  • Related