spo*_*993 0 powershell arraylist powershell-3.0 powershell-4.0
我定义了以下变量
$A = New-Object -TypeName "System.Collections.ArrayList"
Run Code Online (Sandbox Code Playgroud)
现在我n向它添加元素:
$A.Add(1..n)
Run Code Online (Sandbox Code Playgroud)
现在我想将每个元素分成$A几p部分k(如果 ,最后一个可能有较少的元素p*k>$A.count)。我怎么做?
您可以使用函数将数组拆分为多个较小的数组。在此处找到的该函数的稍微改编版本下方:
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" }
}
# when the given ChunkSize is larger or equal to the number of items in the array
# use TWO unary commas to return the array as single sub array of the result.
if ($ChunkSize -ge $items) { return ,,$Array }
$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
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以像这样使用它:
$p = 4 # the number of parts you want
$subArrays = Split-Array $A.ToArray() -Parts $p
Run Code Online (Sandbox Code Playgroud)
或者
$k = 4 # the max number items in each part
$subArrays = Split-Array $A.ToArray() -ChunkSize $k
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |