Powershell将一个长数组分成长度为N的数组数组?

ca9*_*3d9 3 powershell

例如,给定一个列表1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8和一个数字4,它返回一个长度为4的列表列表,即 (1, 2, 3, 4), (5, 6, 7, 8), (1, 2, 3, 4), (5, 6, 7, 8).

基本上我想在Powershell中实现以下Python代码.

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)
Run Code Online (Sandbox Code Playgroud)

以下脚本返回17而不是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
Run Code Online (Sandbox Code Playgroud)

小智 21

这有点旧,但我想我会抛出用于将数组拆分成块的方法.您可以将Group-Object与构造属性一起使用:

$bigList = 1..1000

$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 100

$groups = $bigList | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }
Run Code Online (Sandbox Code Playgroud)

$groups将是GroupInfo对象的集合; 在这种情况下,每个组将有正好100个元素(可以作为$groups[0].Group,$groups[1].Group等等访问.)我使用计数器的对象属性来避免-Property脚本块中的作用域问题,因为一个简单的$i++不回写到原始变量.或者,您可以使用$script:counter = 0$script:counter++在没有自定义对象的情况下获得相同的效果.


Dou*_*nke 10

在2009年的PowerShell Split-Every Function中写了这个

可能可以改进.

Function Split-Every($list, $count=4) {
    $aggregateList = @()

    $blocks = [Math]::Floor($list.Count / $count)
    $leftOver = $list.Count % $count
    for($i=0; $i -lt $blocks; $i++) {
        $end = $count * ($i + 1) - 1

        $aggregateList += @(,$list[$start..$end])
        $start = $end + 1
    }    
    if($leftOver -gt 0) {
        $aggregateList += @(,$list[$start..($end+$leftOver)])
    }

    $aggregateList    
}

$s = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8

$r = Split-Every $s 4

$r[0]
""
$r[1]
""
$r[2]
""
$r[3]
Run Code Online (Sandbox Code Playgroud)


Sha*_*evy 5

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
Run Code Online (Sandbox Code Playgroud)

  • 接受的解决方案仅适用于连续的整数.例如,当$ i为0时,$ a [$ i]为1而$ a [$ i + 3]为4.因此1 .. 4将起作用.但正确的解决方案是`$ z = for($ i = 0; $ i -lt $ a.length; $ i + = 4){,($ a [$ i ..($ i + 3)])}` (2认同)

Hao*_*shu 5

使用 提供解决方案select。不用担心能否$list.Count被 整除$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 ',' }
Run Code Online (Sandbox Code Playgroud)

输出:

1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
17
Run Code Online (Sandbox Code Playgroud)