dounang1974 2018-09-27 23:46
浏览 652
已采纳

Python的list.pop()方法的Go惯用法是什么?

In Python, I have the following:

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

In converting this to Go, I am looking for a similar way of retrieving an item from a slice by index, doing something with it, then putting the original item at the end of my slice.

From here, I have arrived at the following:

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

But this fails at the end of lists:

panic: runtime error: slice bounds out of range

How would I idiomatically translate this slice.pop() into Go?

  • 写回答

5条回答 默认 最新

  • douzhajie7168 2018-09-28 00:04
    关注

    The "Cut" trick in the linked document does what you want:

    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.
    

    Note that if you try to make a one-liner out of the get-and-cut operations you'll get unexpected results due to the tricky behavior of multiple assignments in which functions are called before other expressions are evaluated:

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

    You can work around by wrapping the element access operation in any function call, such as the identity function:

    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}
    

    However, at that point it's probably more clear to use separate assignments.

    For completeness, a "cut" function and its usage could look like this:

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?