我如何比较两个数组,删除类似的项目,而不需要通过整个数组迭代? [英] How can I compare two arrays, removing similar items, without iterating through the whole array?

查看:195
本文介绍了我如何比较两个数组,删除类似的项目,而不需要通过整个数组迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以比较两个阵列和移除相等(如果它们是相同的索引)的值,而无需通过两个阵列迭代?下面是一个例子:

Is it possible to compare two arrays and remove the values that are equal (if they are at the same index), without iterating through both arrays? Here is an example:

$array1 = @(1,2,3,4,5,6,7,23,44)
$array2 = @(1,1,3,4,5,7,6,23,45)

$array3 = $sudo_compare_function $array1 $array2

其中, $ ARRAY3 现在将包含索引数组,其中 $数组2 $数组1 数组:

where $array3 would now contain an array of indexes where $array2 is different from $array1 array:

(1,5,6,8)

如果没有这样的事情,有没有一种简单的方法做同样的事情,而无需通过两个数组迭代?

If there isn't something like this, is there an easy way to do something similar without iterating through both arrays?

推荐答案

使用比较对象 cmdlet来获取不同值的数组:

Use the Compare-Object cmdlet to get an array of differing values:

$array1 = @(1,2,3,4,5,6,7,23,44)
$array2 = @(1,1,3,4,5,7,6,23,45)

$array3 = @(Compare-Object $array1 $array2 | select -Expand InputObject

有关比较只是相应的指标,你必须手动进行比较:

For comparing just the corresponding indexes you'll have to manually make the comparison:

function Compare-Indexes($a1, $a2) {
  $minindex = [math]::Min($a1.Length, $a2.Length)
  $maxindex = [math]::Max($a1.Length, $a2.Length)

  for ($i = 0; $i -le $minindex; $i++) {
    if ( $a1[$i] -ne $a2[$i] ) { $i }
  }
  for ( $i = $minindex + 1; $i -le $maxindex; $i++ ) { $i }
}

$array1 = @(1,2,3,4,5,6,7,23,44)
$array2 = @(1,1,3,4,5,7,6,23,45)

$array3 = Compare-Indexes $array1 $array2

这篇关于我如何比较两个数组,删除类似的项目,而不需要通过整个数组迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆