Go:比较两个切片并删除多个索引

huangapple go评论87阅读模式
英文:

Go: compare two slices and delete multiple indices

问题

如何循环遍历两个切片并根据比较删除多个索引?我尝试了以下代码,但结果出现错误“panic: runtime error: slice bounds out of range.”

package main

import (
	"fmt"
)

func main() {
	type My struct {
		SomeVal string
	}

	type Other struct {
		OtherVal string
	}

	var MySlice []My
	var OtherSlice []Other

	MySlice = append(MySlice, My{SomeVal: "abc"})
	MySlice = append(MySlice, My{SomeVal: "mno"})
	MySlice = append(MySlice, My{SomeVal: "xyz"})

	OtherSlice = append(OtherSlice, Other{OtherVal: "abc"})
	OtherSlice = append(OtherSlice, Other{OtherVal: "def"})
	OtherSlice = append(OtherSlice, Other{OtherVal: "xyz"})

	for i, a := range MySlice {
		for _, oa := range OtherSlice {
			if a.SomeVal == oa.OtherVal {
				MySlice = MySlice[:i+copy(MySlice[i:], MySlice[i+1:])]
			}
		}
	}

	fmt.Println(MySlice)
}

注意:上述代码在只有一个匹配项时有效。当有两个匹配项时会出现错误。

英文:

How do you loop over two slices and delete multiple indices, based on the comparison? I tried the following, but it results in an error "panic: runtime error: slice bounds out of range."

package main

import (
	"fmt"
)

func main() {
	type My struct {
		SomeVal string
	}

	type Other struct {
		OtherVal string
	}

	var MySlice []My
	var OtherSlice []Other

	MySlice = append(MySlice, My{SomeVal: "abc"})
	MySlice = append(MySlice, My{SomeVal: "mno"})
	MySlice = append(MySlice, My{SomeVal: "xyz"})

	OtherSlice = append(OtherSlice, Other{OtherVal: "abc"})
	OtherSlice = append(OtherSlice, Other{OtherVal: "def"})
	OtherSlice = append(OtherSlice, Other{OtherVal: "xyz"})

	for i, a := range MySlice {
		for _, oa := range OtherSlice {
			if a.SomeVal == oa.OtherVal {
				MySlice = MySlice[:i+copy(MySlice[i:], MySlice[i+1:])]
			}
		}
	}

	fmt.Println(MySlice)
}

http://play.golang.org/p/4pgxE3LNmx

Note: the above works if only one match is found. The error happens when two matches are found.

答案1

得分: 0

好的,以下是翻译好的内容:

好的,所以问题是,一旦从切片中删除一个索引,剩余的索引位置会发生变化,导致循环计数出错。通过减少循环计数变量来解决了这个问题。

for i := 0; i < len(MySlice); i++ {
    for _, oa := range OtherSlice {
        if MySlice[i].SomeVal == oa.OtherVal {
            MySlice = append(MySlice[:i], MySlice[i+1:]...)
            i--
            break
        }
    }
}
英文:

Okay, so that was the thing, once an index is remove from the slice the remaining indices shift position, throwing the loop count off. The issue was resolved by decrementing the loop count variable.

for i := 0; i &lt; len(MySlice); i++ {
    for _, oa := range OtherSlice {
        if MySlice[i].SomeVal == oa.OtherVal {
                MySlice = append(MySlice[:i], MySlice[i+1:]...)
		        i--
		        break
        }
    }
}

huangapple
  • 本文由 发表于 2016年3月20日 03:11:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/36105980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定