Python的list.pop()方法的Go成语是什么?

Mit*_*ops 2 list go slice

在Python中,我有以下内容:

i = series.index(s) # standard Python list.index() function
tmp = series.pop(i)
blah = f(tmp)
series.append(tmp)
Run Code Online (Sandbox Code Playgroud)

在将其转换为Go时,我正在寻找一种类似的方法,通过索引从切片中检索项目,对其执行某些操作,然后将原始项目放在切片的末尾.

这里开始,我得出以下结论:

i = Index(series, s) // my custom index function...
tmp, series = series[i], series[i+1:]
blah := f(tmp)
series = append(series, tmp)
Run Code Online (Sandbox Code Playgroud)

但是这在列表末尾失败了:

panic: runtime error: slice bounds out of range
Run Code Online (Sandbox Code Playgroud)

我怎么会习惯性地把它翻译slice.pop()成Go?

mae*_*ics 5

链接文档中的"剪切"技巧可以满足您的需求:

xs := []int{1, 2, 3, 4, 5}

i := 0 // Any valid index, however you happen to get it.
x := xs[i]
xs = append(xs[:i], xs[i+1:]...)
// Now "x" is the ith element and "xs" has the ith element removed.
Run Code Online (Sandbox Code Playgroud)

请注意,如果您尝试使用get-and-cut操作制作单行程,则会因为在评估其他表达式之前调用函数的多个赋值的棘手行为而得到意外结果:

i := 0
x, xs := xs[i], append(xs[:i], xs[i+1:]...)
// XXX: x=2, xs=[]int{2, 3, 4, 5}
Run Code Online (Sandbox Code Playgroud)

您可以通过在任何函数调用中包装元素访问操作来解决此问题,例如身份函数:

i := 0
id := func(z int) { return z }
x, xs := id(xs[i]), append(xs[:i], xs[i+1:]...)
// OK: x=1, xs=[]int{2, 3, 4, 5}
Run Code Online (Sandbox Code Playgroud)

但是,在这一点上,使用单独的分配可能更清楚.

为了完整性,"剪切"功能及其用法可能如下所示:

func cut(i int, xs []int) (int, []int) {
  y := xs[i]
  ys := append(xs[:i], xs[i+1:]...)
  return y, ys
}

t, series := cut(i, series)
f(t)
series = append(series, t)
Run Code Online (Sandbox Code Playgroud)


Vor*_*ung 5

如果你想编写一个以类似于 python 的方式执行 pop() 的函数,那么你必须传入一个指向对象的指针,以便可以修改对象,因为 pop 既返回值又改变列表

func pop(alist *[]int) int {
   f:=len(*alist)
   rv:=(*alist)[f-1]
   *alist=append((*alist)[:f-1])
   return rv
}

func main() {
n:=[]int{1,2,3,4,5}
fmt.Println(n)
last:=pop(&n)
fmt.Println("last is",last)
fmt.Printf("list of n is now %v\n", n)
Run Code Online (Sandbox Code Playgroud)