Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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
like image 565
ca9163d9 Avatar asked Dec 15 '12 00:12

ca9163d9


1 Answers

Providing a solution using select. It doesn't need to worry whether $list.Count can be divided by $chunkSize.

function DivideList {
    param(
        [object[]]$list,
        [int]$chunkSize
    )

    for ($i = 0; $i -lt $list.Count; $i += $chunkSize) {
        , ($list | select -Skip $i -First $chunkSize)
    }
}

DivideList -list @(1..17) -chunkSize 4 | foreach { $_ -join ',' }

Output:

1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
17
like image 179
Haoshu Avatar answered Nov 15 '22 18:11

Haoshu