Equivalent of itemgetter in golang

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

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循环:

package main

import (
	"fmt"
)

func main() {
	a := make([][]int, 3)
	a[0] = []int{1, 2}
	a[1] = []int{2, 3}
	a[2] = []int{7, 4}

	b := make([]int, len(a))
	for i, v := range a {
		if len(v) > 0 {
			b[i] = v[0]
		}
	}
	fmt.Println(b)
}

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

英文:

The equivalent in Go would be a for loop:

package main

import (
	"fmt"
)

func main() {
	a := make([][]int, 3)
	a[0] = []int{1, 2}
	a[1] = []int{2, 3}
	a[2] = []int{7, 4}

	b := make([]int, len(a))
	for i, v := range a {
		if len(v) > 0 {
			b[i] = v[0]
		}
	}
	fmt.Println(b)
}

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:

确定