3

好的,我有一些需要使用 PowerShell 组合的哈希表。以下是格式示例:

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "3";
            "B" = "5";
            "C" = "7"}

我需要合并这些表以创建下表:

$newTable = @{"A" = "1,2,3";
              "B" = "3,4,5";
              "C" = "5,6,7"}

基本上,需要比较键和值。如果值不同,则需要将它们相加。谢谢!

4

3 回答 3

1

这是一种略有不同的方法:

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "3";
            "B" = "5";
            "C" = "7"}

$ht = $table1.Clone()
$table2.GetEnumerator() | % {$ht[$_.Key] += ",$($_.Value)"}
$ht

Name                           Value
----                           -----
C                              5,6,7
A                              1,2,3
B                              3,4,5
于 2012-12-07T22:02:25.153 回答
0

怎么样:

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "2";
            "B" = "5";
            "C" = "7"}

    $newTable = @{}

    function AddToTable($table)
    {
        $table.GetEnumerator() | 
        % {
          if(!$newTable.ContainsKey($_.Key)) {$newTable.Add($_.Key, $_.Value)}
          else {$newTable[$_.Key] += ",$($_.Value)"}
          $newTable[$_.Key] = @($newTable[$_.Key].Split(",") | Get-Unique | Sort-Object) -Join "," 
        }
    }

    AddToTable($table1)
    AddToTable($table2)
于 2012-12-12T13:27:05.473 回答
0

您可以使用该GetEnumerator()方法循环遍历如下值。

$table1如果您的密钥分布不均匀(有些仅存在于 中,而另一些仅存在于 中),这将变得更加复杂,$table2但它适用于您的示例场景。

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "3";
            "B" = "5";
            "C" = "7"}


$NewTable = @{}

$table1.GetEnumerator() | 
%   {
    $NewTable.Add($_.Key, ("$($_.Value),$($table2[$_.Key])"))
    }
于 2012-12-07T21:51:49.187 回答