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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀