【问题标题】:Powershell: Find number of occurrences of a specific numeric value from an integer arrayPowershell:从整数数组中查找特定数值的出现次数
【发布时间】:2020-12-08 20:04:02
【问题描述】:

我有一个如下所示的整数数组,我想在 powershell 中计算该数组中 1 的数量,有人可以帮我吗?

[array]$inputs = 81,11,101,1811,1981
$count = 0
foreach($input in $inputs)
{       
Write-Host "Processing element $input"
$count += ($input -like "*1*" | Measure-Object).Count 
}
Write-Host "Number of 1's in the given array is $count"

它在该数组中只给了我 5 个 1,但预期的答案是 10。任何帮助将不胜感激

【问题讨论】:

    标签: arrays powershell integer


    【解决方案1】:

    从旁注开始:

    不要将$Input用作自定义变量,因为它是保留的自动变量

    对于您正在尝试的内容:
    您遍历数组并检查每个项目(将自动类型转换为字符串)是否为-like1,前面有任意数量的字符,后面有任意数量的字符,无论是真还是假(而不是字符串中的总数)。

    改为
    您可能希望使用 Select-String cmdlet 和 -AllMatches 开关来计算所有匹配项:

    [array]$inputs = 81,11,101,1811,1981
    $count = 0
    foreach($i in $inputs)
    {       
    Write-Host "Processing element $input"
    $count += ($i | Select-String 1 -AllMatches).Matches.Count 
    }
    Write-Host "Number of 1's in the given array is $count"
    

    事实上,感谢 PowerShell member enumeration 功能,您甚至不必为此遍历每个数组项,只需将其简化为:

    [array]$inputs = 81,11,101,1811,1981
    $count = ($Inputs | Select-String 1 -AllMatches).Matches.Count
    Write-Host "Number of 1's in the given array is $count"
    

    Number of 1's in the given array is 10
    

    【讨论】:

    • 感谢您的解决方案和建议。它也有效我已经用下面的脚本解决了这个问题,这是一个正确的方法,[string]$inputs = 89,89,99,909,9899,9989,9.09 $count = 0 foreach($i in $inputs.ToCharArray() ) { if($i -eq "9") {$count++} } Write-Host "给定数组中 9 的个数是 $count"
    【解决方案2】:

    我用下面的脚本解决了上述问题,

    [string]$inputs = 81,11,101,1811,1981
    $count = 0
    foreach($i in $inputs.ToCharArray())
    {  
        if($i -eq "1")   
        {$count++}  
     
    }
    Write-Host "Number of 1's in the given array is $count"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 2020-06-17
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      相关资源
      最近更新 更多