通过切片现有数组列表来创建数组列表的数组列表

问题描述 投票:0回答:1

我定义了以下变量

$A =  New-Object -TypeName "System.Collections.ArrayList"

现在我将n元素添加到其中:

$A.Add(1..n)

现在我想将$A分成p个元素的k部分(如果p*k>$A.count,最后一个元素的元素可能更少)。我该怎么办?

powershell powershell-3.0 powershell-4.0
1个回答
0
投票

您可以使用函数将一个数组拆分为几个较小的数组。在该功能的略带改编的版本下面找到了here

function Split-Array {
    [CmdletBinding(DefaultParametersetName = 'ByChunkSize')]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        $Array,

        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByChunkSize')]
        [ValidateRange(1,[int]::MaxValue)]
        [int]$ChunkSize,

        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByParts')]
        [ValidateRange(1,[int]::MaxValue)]
        [int]$Parts
    )

    $items = $Array.Count
    switch ($PsCmdlet.ParameterSetName) {
        'ByChunkSize'  { $Parts = [Math]::Ceiling($items / $ChunkSize) }
        'ByParts'      { $ChunkSize = [Math]::Ceiling($items / $Parts) }
        default        { throw "Split-Array: You must use either the Parts or the ChunkSize parameter" }
    }

    $result = for ($i = 1; $i -le $Parts; $i++) {
        $first = (($i - 1) * $ChunkSize)
        $last  = [Math]::Min(($i * $ChunkSize) - 1, $items - 1)
        ,$Array[$first..$last]
    }

    return ,$result
}

在您的情况下,您可以像这样使用它:

$p = 4  # the number of parts you want
$subArrays = Split-Array $A.ToArray() -Parts $p

$k = 4  # the max number items in each part
$subArrays = Split-Array $A.ToArray() -ChunkSize $k
© www.soinside.com 2019 - 2024. All rights reserved.