Arrays 获取数组中重复值的索引
我想找到数组中重复值的索引 例如 输入:Arrays 获取数组中重复值的索引,arrays,powershell,Arrays,Powershell,我想找到数组中重复值的索引 例如 输入: $data = @(1, 2, 3, 2, 1) 输出: $indexes = @(3, 4) 内部带有if的Foreach循环应执行以下操作: $data=@(1,2,3,2,1) $uniqueValues=@() $DuplicateSIndex=@() $data | ForEach对象{$counter=0}{ 如果($\不在$uniqueValues中){ $uniqueValues+=$_ }否则{ $DuplicateSIndex+=
$data = @(1, 2, 3, 2, 1)
输出:
$indexes = @(3, 4)
内部带有
if
的Foreach循环应执行以下操作:
$data=@(1,2,3,2,1)
$uniqueValues=@()
$DuplicateSIndex=@()
$data | ForEach对象{$counter=0}{
如果($\不在$uniqueValues中){
$uniqueValues+=$_
}否则{
$DuplicateSIndex+=$counter
}
美元柜台++
}
#输出
PS>$DuplicatesIndex
3.
4.
对于另一种方法,可以将try catch
块与哈希表一起使用
$data = @(1, 2, 3, 2, 1)
$hash = @{}
$indexes = for ($i = 0; $i -lt $data.count; $i++ ) {
try {
$hash.add($data[$i],$i)
}
catch {
$i
continue
}
}
# Output
$indexes
3
4
这里的想法是将每个值作为键添加到哈希表中,并将相应的索引作为值添加到哈希表中。由于[hashtable]
对象只能有唯一的键,因此将引发并捕获异常。在catch块中,我们只输出最终存储在$index
中的索引。continue
语句允许循环递增并保持处理
从算法上讲,这个解决方案几乎与已经提出的解决方案相同。但是,它使用了更有效的
Add()
方法[arraylist]
,而不是在每次迭代期间重建(+=
)一个[array]
。在本例中,性能可以忽略不计,但在较大的数据集中可能值得考虑。这也选择了传统的for
循环,而不是foreach
$uniqueValues = [collections.arraylist]@()
$indexes = for ($i = 0; $i -lt $data.count; $i++) {
if ($uniqueValues -contains $data[$i]) {
$i
}
else {
[void]$uniqueValues.Add($data[$i])
}
}
# Output
$indexes
3
4
此解决方案维护唯一值(
$uniqueValues
)的[arraylist]
。任何非唯一的值,其索引($i
)将输出并存储在$index
中。唯一性是通过使用-contains
运算符将$data
迭代中的当前值与$uniqueValues
中已有的值进行比较来确定的。您还可以使用哈希表来实现此目的:
$data = 1, 2, 3, 2, 1
$hash = @{}
$indexes = for ($i = 0; $i -lt $data.Count; $i++) {
# the value you store in the $hash in the else block is not important
if ($hash.ContainsKey($data[$i])) { $i } else {$hash[$data[$i]] = $true}
}
$indexes
结果:
3
4