0

I want to achieve following things

Example

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

and an integer i. Every time I want to get an i-length sub-array from this array. If i=3

Expected/Required Output : get a sub-array [1,2,3] in first time, in second time I get[4,5,6]. Is there anyway to do that efficiently.

Dipen Panchasara
  • 13,480
  • 5
  • 47
  • 57

2 Answers2

0

Try this generator:

def slice_generator(a, i):
    ind =[[j+l for l in range(i)] for j in a[::i][0:-1]]
    for s in ind:
        yield [a[k] for k in s]

To test:

a = range(10)
i = 3
# create 
a_slice_generator = slice_generator(a,i)
# iterate
for slice in a_slice_generator:
   print slice

Result:

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]

You can also next(a_slice_generator) to move to the next slice.

mengg
  • 310
  • 2
  • 9
0

Try This

Use Of array_chunk.

$input_array = array(1,2,3,4,5,6,7,8,9,10,11,12);
print_r(array_chunk($input_array, 3));

output

 Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
        )
    [3] => Array
        (
            [0] => 10

        )


)
Sumit patel
  • 3,807
  • 9
  • 34
  • 61