arrays - 比较两个数组,如果值在数组中,则添加到列表中,如果不是,则将值添加到另一个列表中。没有重复
问题描述
请查看代码中的注释,看看您是否可以帮助我解决这个问题。我正在检查 $arr1 中的值是否在 $arr2 中。如果是,则将其添加到列表中,如果不是,则将其添加到另一个列表中。确保两个列表/数组都没有重复项。
$arr1 = @(1,2,3,4,4,2,5,7,9,9,1)
$arr2= @(5,1,2,3,6,8,1)
$NotinList = @()
$inList = @()
$counter = 0
for ($i = 0; $i -lt $arr1.length; $i++){
for( $j = 0; $j -lt $arr2.length; $j++ ){
if($arr1[$i] -ne $arr2[$j]){ #check to see if value from $arr1 is in $arr2
for($k = 0; $k -lt $NotinList.length; $k++){ #Traverse through empty array
write-host $arr1[$i]
if($NotinList[$k] -ne $arr1[$i]){ # *^ if empty array does not alreadycontain item from big $arr1, add it.
$NotinList += $arr1[$i]
}
}
}
else{
$inList += $arr1[$i]
#how would I remove duplicates from number in list since there are repeating numbers in $arr1 that are not in $arr2.
}
}
$counter++ #keep track may use for something else??
}
解决方案
我会先消除重复项,然后使用Where()
数组运算符将数组拆分为变量。
$arr1 = 'a','b','b','c','d','e','e','f','g'
$arr2 = 'a','b','c','g'
# not in list = d, e, f
# in list = a, b, c, g
$inlist,$notinlist = ($arr1 | Get-Unique).Where({$_ -in $arr2},'split')
现在这是每个包含的内容
$notinlist
d
e
f
$inlist
a
b
c
g
推荐阅读
- java - 如何正确使用抽象类(测试问题)
- firewall - MikroTik 伪装 Vs。src-nat
- jquery - jQuery Div 切换器
- c# - 从代码 sqlite 获取插入日期错误
- makefile - 有没有办法打印生成文件中定义/可见的所有变量?
- emotion - 情感包问题-React
- python - 将 Pine 脚本转换为 Python
- javascript - 使用数组的映射创建html时子组件不会立即重新渲染
- visual-studio-code - 在 VSCode 中按 CTRL 时隐藏自动建议弹出窗口
- windows - 从其他批处理文件中调用批处理文件时,只有第一个被调用