tech.guitarrapc.cóm

Technical updates

PowerShellでHashTableを使ってオブジェクトをカウントする

さて、オブジェクトのカウントですが、色々なやり方があります。 今回は、HashTableを使った考えていなかった方法があったのでご紹介です。

#PSTip Count occurrences of a word using a hash table

カウント対象

計測対象は以下の文字の個数です。

'three','three','one','three','two','two'

私ならどうするか

私の場合はこのように考えます。

$wordList = 'three','three','one','three','two','two'
$wordList | group $_ | %{[PSCustomObject]@{Value=$_.Name;Count=$_.Count}} | sort Value

改行入れるならこうです。

$wordList = 'three','three','one','three','two','two'
$wordList `
    | group $_ `
    | %{
        [PSCustomObject]@{
            Value=$_.Name;
            Count=$_.Count}
        } `
    | sort Value

Format-Tableでの結果です。

Value Count
----- -----
one       1
three     3
two       2

牟田口先生の案

なるほど…PSCustomObjectはなるべく避けたいか…、納得です。

$wordList = 'three','three','one','three','two','two'
$wordList | group -NoElement $_

結果表示です。

Count Name
----- ----
    3 three
    1 one
    2 two

紹介するやり方

うまくHashTableを使ってます

$wordList = 'three','three','one','three','two','two'
$wordStatistic = $wordList | ForEach-Object -Begin { $wordCounts=@{} } -Process { $wordCounts.$_++ } -End { $wordCounts }
$wordStatistic

結果表示です。

Name                           Value
----                           -----
one                            1
three                          3
two                            2

HashTableのインクリメントでの使い方、面白いです。 PowerShellというより、AWK的な考えな感じもしますがとても興味深かったので参考にどうぞw

単純にこれでは

まぁSelectでもいい気もしますが…んー色々あって余りSelectを使うのは好きじゃないです。

$wordList = 'three','three','one','three','two','two'
$wordList | group $_ | Select Name,Count

Format-Tableでの結果です。

Name  Count
----  -----
three     3
one       1
two       2

速度

ちなみに速度的には…さてさてw

# 私のやり方
TotalSeconds      : 0.0004608

# 牟田口先生のやり方
TotalSeconds      : 0.0002187

# 紹介したHashTableのやり方
TotalSeconds      : 0.00331

# groupしてselect
TotalSeconds      : 0.0004079

なるほ、牟田口先生のやり方でいきましょう。