【问题标题】:Is the a cleaner way to fetch the top value in an array of arrays?获取数组数组中的最高值的更简洁的方法是什么?
【发布时间】:2015-11-03 22:44:37
【问题描述】:

我有一个数组,它们的大小完全不同,但都是整数。我需要做的是找到每个的最高价值,以便以后与某些东西进行比较。不太难,但是当我写出来的时候,第一眼感觉代码几乎不可读。特别是这一行:

$logScaleList[$i][$logScaleList[$i].Length-1] 

因为这个迟钝,还是只是在处理二维数组时,你会有丑陋的嵌套语句?

完整代码在这里:

$logScaleList = [System.Collections.ArrayList]@() 

[void]$logScaleList.Add(@(100,126,158,200,251,316,398,501,631,794,1000,1259,1585,1995,2512,3162,3981,5012,5230))
[void]$logScaleList.Add(@(100,126,158,200,251,316,398,501,631,794,1000,1259,1585,1995,2512,3162,3981,5012,5850))
[void]$logScaleList.Add(@(1000,1259,1585,1995,2512,3162,3981,3162,5012,6310,7390))
[void]$logScaleList.Add(@(1,2,3,4,5,6,8,10,13,16,20,25,32,40,50,63,79,100,126,158,200,251,316,398,501,631,794,1000,1259,1585,1995,2512,3162,3981,5012))
[void]$logScaleList.Add(@(1,2,3,4,5,6,8,10,13,16,20,25,40,50,63,79,100,126,158,200,251,316,398,501,631,794,1000,1259,1585,1995,2512))


for ($i = 0; $i -lt $logScaleList.count; $i++)
{ 
    write-host "Top value is" $logScaleList[$i][$logScaleList[$i].Length-1] 

}

【问题讨论】:

  • 最高值?还是在数组元素 0 中?
  • 嗯,$LogScaleList | ForEach{$_ | Select -Last 1}$LogScaleList | ForEach{$_[-1]},其中任何一个都会为您提供嵌套数组的最后一个值。如果数组不是按顺序传递到Sort,然后传递到Select -Last 1

标签: .net arrays powershell coding-style


【解决方案1】:

您可以使用ForEach-Objectforeach 循环来避免第一个索引运算符:

foreach($List in $LogScaleList){
    $List[$List.Length - 1]
}

您可以通过索引-1 引用最后一项,同时避免使用Length 属性(如果这对您来说看起来不那么难看):

foreach($List in $LogScaleList){
    $List[-1]
}

【讨论】:

    【解决方案2】:

    您可以使用sort cmdlet 对数组进行排序并选择第一项:

    $logScaleList | % { $_ | sort -Descending | select -first 1 }
    

    输出:

    5230
    5850
    7390
    5012
    2512
    

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 2012-02-06
      • 2015-09-09
      • 2010-09-25
      • 2020-11-12
      • 2011-04-23
      • 2012-08-25
      • 1970-01-01
      • 2013-04-15
      相关资源
      最近更新 更多