Equivalent of itemgetter in golang

huangapple go评论113阅读模式
英文:

Equivalent of itemgetter in golang

问题

我正在将一个程序从Python转换为Go语言,并且我有一行代码需要获取嵌套列表中的第一个值:
x_values = map(operator.itemgetter(0), self.coords)
这个命令将[[1,2],[2,3],[7,4]]转换为[1,2,7]

在Go语言中有相应的等价方法吗?

英文:

I'm converting a program from python to golang, and I have this line that gets the first value within a nested list:
x_values = map(operator.itemgetter(0), self.coords)
This command turns [[1,2],[2,3],[7,4]] to [1,2,7].

Is there an equivalent of this in go?

答案1

得分: 2

在Go语言中,等价的是使用for循环:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. a := make([][]int, 3)
  7. a[0] = []int{1, 2}
  8. a[1] = []int{2, 3}
  9. a[2] = []int{7, 4}
  10. b := make([]int, len(a))
  11. for i, v := range a {
  12. if len(v) > 0 {
  13. b[i] = v[0]
  14. }
  15. }
  16. fmt.Println(b)
  17. }

你可以在这里运行代码并查看结果:https://play.golang.org/p/pNz8nQu20D

英文:

The equivalent in Go would be a for loop:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. a := make([][]int, 3)
  7. a[0] = []int{1, 2}
  8. a[1] = []int{2, 3}
  9. a[2] = []int{7, 4}
  10. b := make([]int, len(a))
  11. for i, v := range a {
  12. if len(v) > 0 {
  13. b[i] = v[0]
  14. }
  15. }
  16. fmt.Println(b)
  17. }

https://play.golang.org/p/pNz8nQu20D

huangapple
  • 本文由 发表于 2017年3月12日 05:15:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/42740726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定