在中,描述了用于数组集合操作的单行代码。
我想用哈希表来做这件事,并有一个使用字典的键集的解决方案。为了扩展到值,我使用for循环遍历键的交集,并将值复制到新的结果哈希表中。这看起来不干净。
进一步的研究表明,解决方案与GetEnumerator,这也不是干净的IMHO。
如何将臃肿的循环或枚举数替换为简洁漂亮的一行程序?
源代码如下:
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 $_}发布于 2015-11-21 12:39:05
您可以使用与列表相同的技术,但使用散列表键,如您在操作中所指出的那样。
对于并集和交集,您有一个额外的问题。在两个哈希表之间共有的关键字中,您会保留哪个值?假设您总是将该值保存在第一个哈希表中。然后:
# 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[$_]}https://stackoverflow.com/questions/33823151
复制相似问题