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

标签 list go slice

在 Python 中,我有以下内容:

i = series.index(s) # standard Python list.index() function
tmp = series.pop(i)
blah = f(tmp)
series.append(tmp)

在将其转换为 Go 时,我正在寻找一种类似的方法来按索引从 slice 中检索项目,对其进行处理,然后将原始项目放在 slice 的末尾。

来自 here ,我得出了以下结论:

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

但这在列表末尾失败了:

panic: runtime error: slice bounds out of range

我将如何以惯用的方式将此 slice.pop() 翻译成 Go?

最佳答案

"Cut" trick在链接文档中做你想做的:

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.

请注意,如果您尝试从 get-and-cut 操作中创建一个单行代码,您将得到意想不到的结果,这是由于多重赋值的棘手行为,其中函数在其他表达式被求值之前被调用 :

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

您可以通过在任何函数调用中包装元素访问操作来变通,例如标识函数:

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}

但是,此时使用单独的赋值可能更清楚。

为了完整起见,“剪切”函数及其用法可能如下所示:

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)

关于list - Python 的 list.pop() 方法的 Go 习语是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546470/

相关文章:

java - 类型不匹配 : cannot convert from List<String> to ArrayList<String>

html - 使用 golang 解析损坏的 HTML

linux - 在 Alpine Linux Docker 的路径中找不到安装的 Go 二进制文件

arrays - 切片与数组的比较在 Rust 中如何工作?

arrays - 戈朗 : array is empty after call a method that adds items to the array

python - 在python中将列表传递给sql

Python - 基于键/值标识的分组/合并字典

c# - 列出可用的网络打印机(也包括未安装的)

go - 如何评估外部go源代码 "dynamically"?

list - 从F#中的列表中切片类似的功能