powershell

Powershell break a long array into a array of array with length of N in one line?


For example, given a list 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8 and a number 4, it returns a list of list with length of 4, that is (1, 2, 3, 4), (5, 6, 7, 8), (1, 2, 3, 4), (5, 6, 7, 8).

Basically I want to implement the following Python code in Powershell.

s = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8
z = zip(*[iter(s)]*4)  # Here N is 4
# z is (1, 2, 3, 4), (5, 6, 7, 8), (1, 2, 3, 4), (5, 6, 7, 8)

The following script returns 17 instead of 5.

$a = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,0
$b = 0..($a.Length / 4) | % {  @($a[($_*4)..($_*4 + 4 - 1)]) } 
$b.Length

Solution

  • PS> $a = 1..16
    PS> $z=for($i=0; $i -lt $a.length; $i+=4){ ,($a[$i]..$a[$i+3])}
    PS> $z.count
    4    
    
    PS> $z[0]
    1
    2
    3
    4
    
    PS> $z[1]
    5
    6
    7
    8
    
    PS> $z[2]
    9
    10
    11
    12
    
    PS> $z[3]
    13
    14
    15
    16