arrays - Powershell中数组成员的统计分析
问题描述
[数组]$a=foreach($l in $l){xxxx}
$a 输出:</p>
@{D=xxx;p=x;pc=xxx;d=a;t=0-1} @{D=xxx;p=x;pc=xxx;d=b;t=0-1} @{D=xxx;p=x;pc=xxx;d=b;t=0-1} @{D=xxx;p=x;pc=xxx;d=a;t=1-2}
@{D=xxx;p=x;pc=xxx;d=c;t=1-2} @{D=xxx;p=x;pc=xxx;d=a;t=1-2}
......
$a[0] 输出:
@{D=xxx;p=x;pc=xxx;d=a;t=0-1}
我想要的是当 t 相同时 d 的出现次数。并将次数放入每个值中。
转换为 JSON 后
我要什么:</p>
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"a",
"t":"0-1",
"Number":"1"},
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"b",
"t":"0-1",
"Number":"2"},
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"a",
"t":"1-2",
"Number":"2"},
{"D":"xxx",
"p":"x",
"pc":"xxx",
"d":"c",
"t":"1-2",
"Number":"1"}
解决方案
所以这里再次基本上是相同的答案,但现在,完全不针对您的真正问题。
# recreate the array of objects (renamed d to d2 - cannot have duplicate property names
$a = @(
[pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'a'; t = '0-1' }
[pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'b'; t = '0-1' }
[pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'b'; t = '0-1' }
[pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'a'; t = '1-2' }
[pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'c'; t = '1-2' }
[pscustomobject]@{D = 'xxx'; p = 'x'; pc = 'xxx'; d2 = 'a'; t = '1-2' }
)
# use group-object to group the objects by properties d2 and t
# get the count of the group and add it to first item in the group
# then output one item per group with the new count property
# last, pipe to ConvertTo-Json to create the json
$a | Group-Object d2, t |
ForEach-Object {
$item = $_.Group[0]
$item | Add-Member -NotePropertyName 'Number' -NotePropertyValue $_.Group.Count
$item
} | ConvertTo-Json
输出
[
{
"D": "xxx",
"p": "x",
"pc": "xxx",
"d2": "a",
"t": "0-1",
"Number": 1
},
{
"D": "xxx",
"p": "x",
"pc": "xxx",
"d2": "b",
"t": "0-1",
"Number": 2
},
{
"D": "xxx",
"p": "x",
"pc": "xxx",
"d2": "a",
"t": "1-2",
"Number": 2
},
{
"D": "xxx",
"p": "x",
"pc": "xxx",
"d2": "c",
"t": "1-2",
"Number": 1
}
]
推荐阅读
- xml - 完成后将变量保存在 .awk 文件中以供下次运行
- javascript - Apollo 客户端订阅的缓存策略未按预期工作
- deep-learning - 双深度 Q 学习:下一个状态总是错误的
- reactjs - 许多小的 react.CreateElement 对同一文档的性能影响?
- python - calcOpticalFlowFarneback 的结果是否需要在翘曲中进行一些处理?
- javascript - SVG 动画只能在网站的正确页面/部分上启动
- python-3.x - @client.event 从一个为假的 if 条件返回一个输出
- azure - Azure DevOps 中的应用服务名称显示未找到任何结果
- kotlin - 当语言为 kotlin 时,Tarantool 墨盒-springdata(tarantool 的弹簧数据)不起作用
- drupal - 无法在我的 drupal 9 中打开自定义模块