英文:
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 < len(MySlice); i++ {
for _, oa := range OtherSlice {
if MySlice[i].SomeVal == oa.OtherVal {
MySlice = append(MySlice[:i], MySlice[i+1:]...)
i--
break
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论