【问题标题】:Find missing rows in Powershell 2D arrays在 Powershell 2D 数组中查找缺失的行
【发布时间】:2012-05-23 08:53:26
【问题描述】:

我有 2 个数组,每个数组有 2 个字段(例如“项目”和“价格”)。

以下是我的1个数组的get-member结果(实际上两个数组具有相同的结构)

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
item        NoteProperty System.String field1=computer 
price       NoteProperty System.String field2=2000     

我需要在数组 $shopA 中找到未在数组 $shopB 中找到的项目。我现在使用 2 个循环来查找丢失的项目。

$missing = @()
foreach ($itemA in $shopA) {
  $found = 0
  foreach ($itemB in $shopB) {
    if ($itemB.item -eq $itemA.item) {
      $found = 1
    }
  }
  if ($found = 0) {
    $missing += $itemA
  }
}

这种方法对我有用,但我的 2 个数组非常大,我想要一个比循环遍历整个数组更快的方法...

我一直在寻找一种更好的方法来做到这一点,比较对象几乎可以完成这项工作,但所有示例似乎都只适用于一维数组。

谢谢

【问题讨论】:

    标签: arrays powershell


    【解决方案1】:

    据我所知,您确实有两个一维数组,尽管您声称相反。

    寻找丢失物品的简单方法是

    $missing = $shopA | ? { $x = $_; !($shopB | ? {$_.item -eq $x.item})}
    

    但是,这始终是 O(n²);为了让它更快,你可以先从 $shopB 收集所有项目,这使得检查存在 O(1),而不是 O(n):

    $hash = @{}
    $shopB | %{ $hash[$_.item] = 1 }
    $missing = $shopA | ?{ !$hash.ContainsKey($_.item) }
    

    【讨论】:

    • 谢谢乔伊。我想知道是否可以在不构建另一个哈希表的情况下解决问题,但如果这是最好的方法,那么我将创建一个哈希表。
    • 你提到了大数组,所以从性能的角度来看,你应该创建哈希表来检查存在。
    • 如果我需要创建一个新表,我也会尝试使用 compare-object。非常感谢,您的建议很有帮助。
    【解决方案2】:

    这样的?

     $shopA= @(1, 2, 3, 4)
     $shopB= @(4, 3, 5, 6)
     $shopB | where { $shopA -notcontains $_  }
    

    【讨论】:

    • 谢谢大卫。如果数组是二维的怎么办?我已经用我的数据尝试过你的建议,但没有奏效。
    • 请注意,它们的项目具有属性,因此正常的相等性可能无法直接工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2022-12-03
    • 2011-11-11
    相关资源
    最近更新 更多