【问题标题】:Union and Intersection of Hashtables in PowerShellPowerShell中哈希表的并集和交集
【发布时间】:2016-02-22 17:34:38
【问题描述】:

Union and Intersection in PowerShell? 中描述了用于数组集合操作的酷单行。

我想用哈希表来做这件事,并有一个使用字典键集的解决方案。为了扩展到值,我使用 for 循环遍历键的交集并将值复制到新的结果哈希表。这看起来不干净。

进一步的研究表明 GetEnumerator 的解决方案也不是干净的恕我直言。

如何用简洁漂亮的单行代码替换臃肿的 for 循环或枚举器?

源码如下:

http://paste.ubuntu.com/13362425/

# import csv
$a = Import-Csv -Path A.csv -Delimiter ";" -Header "Keys","Values"
$b = Import-Csv -Path B.csv -Delimiter ";" -Header "Keys","Values"

# Make nice hashtables for further use
$AData = @{}
foreach($r in $a)
  { $AData[$r.Keys] = $r.Values }
$BData = @{}
foreach($r in $b)
  { $BData[$r.Keys] = $r.Values }

# Set difference to find missing entries
$MissingA = $AData.Keys | ?{-not ($BData.Keys -contains $_)}

# I don't know how to do set-operations on hashtables yet. So use keysets and copy data (lame!)
$MissingAData = @{}
foreach($k in $MissingA)
{
    $MissingAData[$k] = $AData[$k]
}

# Intersection
$Common = $AData.Keys | ?{$BData.Keys -contains $_}

【问题讨论】:

  • 您是只对“值”感兴趣还是对整个键值对感兴趣?
  • 整个键值对

标签: powershell


【解决方案1】:

您可以使用与列表相同的技术,但使用哈希表键,正如您在 OP 中指出的那样。

对于并集和交集,您还有一个问题。在两个哈希表之间的共同键中,您将保留哪个值?假设您将始终将值保留在第一个哈希表中。那么:

# need clone to prevent .NET exception of changing hash while iterating through it
$h1clone = $hash1.clone()

# intersection
$h1clone.keys | ? {$_ -notin $hash2.keys} | % {$hash1.remove($_)}

# difference: $hash1 - $hash2
$h1clone.keys | ? {$_ -in $hash2.keys}    | % {$hash1.remove($_)}

# union. Clone not needed because not iterating $hash1
$hash2.keys   | ? {$_ -notin $hash1.keys} | % {$hash1[$_] = $hash2[$_]}

或者你可以这样做避免克隆并创建一个新的哈希表

# intersection
$newHash = @{}; $hash1.keys | ? {$_ -in $hash2.keys} | % {$newHash[$_] = $hash1[$_]}

# difference: $hash1 - $hash2
$newHash = @{}; $hash1.keys | ? {$_ -notin $hash2.keys} | % {$newHash[$_] = $hash1[$_]}

【讨论】:

  • 像一个魅力一样工作,感谢关于在交叉点保留哪个值的问题的说明。
  • 很聪明,很好
猜你喜欢
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2014-01-24
  • 2021-12-15
  • 2011-05-14
  • 1970-01-01
相关资源
最近更新 更多