在 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/