cra*_*aig 3 arrays powershell data-partitioning
我想根据变量将单个数组转换为一组较小的数组。所以,0,1,2,3,4,5,6,7,8,9将成为0,1,2,3,4,5,6,7,8,9当大小为3。
我目前的做法:
$ids=@(0,1,2,3,4,5,6,7,8,9)
$size=3
0..[math]::Round($ids.count/$size) | % {
# slice first elements
$x = $ids[0..($size-1)]
# redefine array w/ remaining values
$ids = $ids[$size..$ids.Length]
# return elements (as an array, which isn't happening)
$x
} | % { "IDS: $($_ -Join ",")" }
Run Code Online (Sandbox Code Playgroud)
产生:
IDS: 0
IDS: 1
IDS: 2
IDS: 3
IDS: 4
IDS: 5
IDS: 6
IDS: 7
IDS: 8
IDS: 9
Run Code Online (Sandbox Code Playgroud)
我希望它是:
IDS: 0,1,2
IDS: 3,4,5
IDS: 6,7,8
IDS: 9
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
cls
$ids=@(0,1,2,3,4,5,6,7,8,9)
$size=3
<#
Manual Selection:
$ids | Select-Object -First 3 -Skip 0
$ids | Select-Object -First 3 -Skip 3
$ids | Select-Object -First 3 -Skip 6
$ids | Select-Object -First 3 -Skip 9
#>
# Select via looping
$idx = 0
while ($($size * $idx) -lt $ids.Length){
$group = $ids | Select-Object -First $size -skip ($size * $idx)
$group -join ","
$idx ++
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见:
function Slice-Array
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$True)]
[String[]]$Item,
[int]$Size=10
)
BEGIN { $Items=@()}
PROCESS {
foreach ($i in $Item ) { $Items += $i }
}
END {
0..[math]::Floor($Items.count/$Size) | ForEach-Object {
$x, $Items = $Items[0..($Size-1)], $Items[$Size..$Items.Length]; ,$x
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
@(0,1,2,3,4,5,6,7,8,9) | Slice-Array -Size 3 | ForEach-Object { "IDs: $($_ -Join ",")" }
Run Code Online (Sandbox Code Playgroud)
您可以使用,$x而不只是$x.
about_Operators文档中的部分有这样的内容:
, Comma operator
As a binary operator, the comma creates an array. As a unary
operator, the comma creates an array with one member. Place the
comma before the member.
Run Code Online (Sandbox Code Playgroud)