英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论