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条)

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面