我一般不太擅長編碼,但在 Powershell 中也不擅長,所以我希望有人能在這里支持我。我有一個數字串列,我想遍歷每個專案并檢查它是否比最后一個專案大 1( 1)。如果是,它應該將它添加到一個新串列中,并且輸出應該如下所示: numbers = @("12","50","5041-5043")而不是numbers = @("12","50","5041","5042","5043")基本上我想要連接預先排序的數字范圍。
任何建議或指導表示贊賞
numbers = @("12","50","5041","5042","5043")
count = 0
while(numbers.Length){
if(#ItemInList[$count] -eq #nextItemInList[$count 1]){
#put in range
}
}
uj5u.com熱心網友回復:
這是您可以做到的一種方法,希望行內注釋可以幫助您理解邏輯。
$numbers = "0","1","2","12","50","5041","5042","5043","8888","8889"
$firstInRange = $null
$result = for($i = 0; $i -lt $numbers.Count; $i ) {
# Convert this number to int so we can compare it
[int] $thisNumber = $numbers[$i]
# if this number 1 is equal to the next number
if($thisNumber 1 -eq $numbers[$i 1]) {
# if `$firstInRange` is populated, go to next iteration
if($null -ne $firstInRange) { continue }
# else, this is the first number in range, assign it
$firstInRange = $thisNumber
# and skip the next logic
continue
}
# if previous condition was `$false` and `$firstInRange` is populated
if($null -ne $firstInRange) {
# this is signal to output the range, concatenate first and last
$firstInRange, $thisNumber -join '-'
# clear this variable for next capture
$firstInRange = $null
# and skip the next logic
continue
}
# if none of the before were `$true`, just output this number
$thisNumber
}
$result -join ', ' # => 0-2, 12, 50, 5041-5043, 8888-8889
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474182.html
標籤:电源外壳
