arrays - Powershell:从整数数组中查找特定数值的出现次数
问题描述
我有一个如下所示的整数数组,我想在 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。任何帮助将不胜感激
解决方案
从旁注开始:
不要
$Input
用作自定义变量,因为它是保留的自动变量
对于您正在尝试的内容:
您遍历数组并检查每个项目(将自动类型转换为字符串)是否前面-like
有1
任意数量的字符,并且后面有任意数量的字符,这些字符是真或假(而不是字符串中的总数)。
相反
,您可能希望将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成员枚举功能,您甚至不必为此遍历每个数组项,只需将其简化为:
[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
推荐阅读
- node.js - .catch((err) => { 在第一个括号处出错
- javascript - 以前可以通过 Javascript 访问 HTTP 请求
- x86 - CPU 如何“准确地”读取和执行 bios 代码?
- sql - 使用默认值填充雪花表而不从文件数据中选择默认列值
- python - Python中的求和值
- python - 检查字符串以在 spark 数据框中创建新列
- python - inverseTransform 是否应该是模型进行预测的静态方法
- c# - 如何使用 c# 将 1606813200000 转换为 2020-12-01T09:00:00.000Z
- mysql - 我如何在 sql 中将我的 id null 修改为 not null
- javascript - 从浏览器录制视频并流式传输到 Youtube/Twitch 时,如何使用 ffmpeg 添加音频?