Powershell数组-加入前获取上下索引值

时间:2018-11-13 11:25:07

标签: arrays powershell indexing find mergesort

我有两个解析的PowerShell对象:$ Table1和$ Table2。 解析表1,我得到一个时间戳:$ TimeStamp,我需要为其找到表2中两个最接近的值。

$Table2 looks like this:


Price  TimeStamp       
-----  ----------------       
0.0597 1542056680.72746
0.0584 1542056650.34414
0.0555 1542056197.46668
0.0551 1542056167.28967

$TimeStamp = 1542056303
$Table2 is already sorted by TimeStamp

我的目标是有效地返回$ Table2的上,下索引(我的问题的核心)。然后,我将在两个时间戳和两个价格之间进行线性插值,以获得$ Price的值。

答案中不需要线性插值部分,这只是出于上下文目的。

干杯

菲利普

2 个答案:

答案 0 :(得分:2)

我会那样做:

$TimeStamp = 1542056303

# find closest before given timestamp
$Table2 | Where-Object { [int]$_.Timestamp -gt $TimeStamp } | Select-Object -Last 1

# find closest after given timestamp
$Table2 | Where-Object { [int]$_.Timestamp -lt $TimeStamp } | Select-Object -First 1

答案 1 :(得分:1)

Imo如果存储行,则不需要索引。

  • 重复表并检查当前值是否小于或等于$ TimeStamp
  • 如果当前行未存储为$ Upper
  • 如果-le将行存储为$ Lower并中断foreach

## Q:\Test\2018\11\13\SO_53279995.ps1

$TimeStamp = 1542056303
$table2 = Import-Csv '.\table2.csv' | Sort-Object TimeStamp -Descending
$Upper = $Null
$Lower = $Null

ForEach ($Row in $table2){
    if([Double]$Row.TimeStamp -le $TimeStamp){
        $Lower = $Row
        Break
    } else {
        $Upper = $Row
    }
}
If ($Upper -and $Lower){
    $Upper
    $Lower
    "Do your interpolation"
} else {
    "can't evaluate nearest values"
}

样本输出

Price  TimeStamp
-----  ---------
0.0584 1542056650.34414
0.0555 1542056197.46668
Do your interpolation