遍历切片并重置索引 – golang

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

Iterating through a slice and resetting the index - golang

问题

我正在遍历一个切片,并逐个选择元素。我遇到的问题是,在删除一个元素后,我应该重置索引或从头开始,但我不确定如何做。

以下是代码的翻译结果:

package main

import (
	"fmt"
)

func main() {
	x := []int{1, 2, 3, 7, 16, 22, 17, 42}
	fmt.Println("我们将从以下切片开始:", x)

	for i, v := range x {
		fmt.Println("当前值为:", v)
		x = append(x[:i], x[i+1:]...)
		fmt.Println("删除后的切片为:", x)
	}
}

输出结果如下:

我们将从以下切片开始: [1 2 3 7 16 22 17 42]
当前值为: 1
删除后的切片为: [2 3 7 16 22 17 42]
当前值为: 3
删除后的切片为: [2 7 16 22 17 42]
当前值为: 16
删除后的切片为: [2 7 22 17 42]
当前值为: 17
删除后的切片为: [2 7 22 42]
当前值为: 42
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
main.main()
	/tmp/sandbox337422483/main.go:13 +0x460

你想知道如何以惯用方式解决这个问题。我立即想到的是从Python中使用i--i = i-1

英文:

I am iterating through a slice in golang and picking off elements one by one. The problem I am having is that after I remove an item I should either reset the index or start from the beginning but I'm not sure how.

package main

import (
	"fmt"
)

func main() {
	x := []int{1, 2, 3, 7, 16, 22, 17, 42}
	fmt.Println("We will start out with", x)

	for i, v := range x {
		fmt.Println("The current value is", v)
		x = append(x[:i], x[i+1:]...)
		fmt.Println("And after it is removed, we get", x)
	}
}

Will Return the following:

We will start out with [1 2 3 7 16 22 17 42]
The current value is 1
And after it is removed, we get [2 3 7 16 22 17 42]
The current value is 3
And after it is removed, we get [2 7 16 22 17 42]
The current value is 16
And after it is removed, we get [2 7 22 17 42]
The current value is 17
And after it is removed, we get [2 7 22 42]
The current value is 42
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
main.main()
	/tmp/sandbox337422483/main.go:13 +0x460

What is the idiomatic way to do this?
I immediately thing i-- or i = i-1 coming from Python.

答案1

得分: 1

我个人更喜欢创建一个副本。但是如果你改变range部分,也可以不创建副本来完成:

package main

import (
	"fmt"
)

func main() {
	x := []int{1, 2, 3, 7, 16, 22, 17, 42}
	fmt.Println("我们将从", x, "开始")

	for i := 0; i < len(x); {
		fmt.Println("当前值为", x[i])
		x = append(x[:i], x[i+1:]...)
		fmt.Println("移除后,我们得到", x)
	}
}
英文:

I personally prefer to create a copy. But also it can be done without if you change range part:

package main

import (
	&quot;fmt&quot;
)

func main() {
	x := []int{1, 2, 3, 7, 16, 22, 17, 42}
	fmt.Println(&quot;We will start out with&quot;, x)

	for i := 0; i &lt; len(x);  {
		fmt.Println(&quot;The current value is&quot;, x[i])
		x = append(x[:i], x[i+1:]...)
		fmt.Println(&quot;And after it is removed, we get&quot;, x)
	}
}

huangapple
  • 本文由 发表于 2017年3月23日 04:10:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/42961730.html
匿名

发表评论

匿名网友

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

确定