使用Powershell,我如何计算数组中每个元素的出现? [英] Using Powershell, how can i count the occurrence of each element in an array?
本文介绍了使用Powershell,我如何计算数组中每个元素的出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个数组:
1 1 1 2 2 3 4 4 4 4 5 5
1 1 1 2 2 3 4 4 4 4 5 5
如何使用Powershell告诉我该数组中每个元素有多少个?
How can I use Powershell to tell me how many of each element there are in that array?
更清楚一点,我应该为每个数组元素分别计数:
To be a little more clear, I should have a separate count for each array element:
元素:计数
1:3
2:2
3:1
4:4
5:2
推荐答案
您可以使用Group-Object
cmdlet:
You can use the Group-Object
cmdlet:
PS> 1,1,1,2,2,3,4,4,4,4,5,5 | group
Count Name Group
----- ---- -----
3 1 {1, 1, 1}
2 2 {2, 2}
1 3 {3}
4 4 {4, 4, 4, 4}
2 5 {5, 5}
如果您想要项的哈希表及其数量,您只需要在其后加上一点ForEach-Object
:
If you want a hashtable for the items and their counts you just need a little ForEach-Object
after it:
$array | group | % { $h = @{} } { $h[$_.Name] = $_.Count } { $h }
这篇关于使用Powershell,我如何计算数组中每个元素的出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文