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

前端 未结 6 2018
梦毁少年i
梦毁少年i 2020-12-18 02:24

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),

6条回答
  •  太阳男子
    2020-12-18 02:34

    @Shay Levy Answer: if you change the value of a to 1..15 then your solution not working anymore ( Peter Reavy comment )

    So this worked for me:

    $a = 1..15
    $z=for($i=0; $i -lt $a.length; $i+=4){if ($a.length -gt ($i+3)) { ,($a[$i]..$a[$i+3])} else { ,($a[$i]..$a[-1])}}
    $z.count
    

提交回复
热议问题