将1维数组与2维数组组合使用`append`函数。

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

go 1d array combine 2d array with append

问题

我有两个一维数组,我想用append将这两个单独的数组合并成一个多维数组。

在Go语言中,如何以最快的方式完成这个操作?

  1. var time []int64
  2. var value []float64
  3. var twoDArray [][]interface{}
  4. // 使用append来合并数组
  5. for i := 0; i < len(time); i++ {
  6. twoDArray = append(twoDArray, []interface{}{time[i], value[i]})
  7. }

在Go语言中,使用append是将数组合并的最佳方式。

英文:

I have two one dimensional array and I want to combine the two single arrays into one multi dimensional array with append.

How would this be done for the fastest in go?

  1. val time []int64
  2. val value []float64
  3. val 2darray [][]int64, float64

Would append be the best way to do this in go?

答案1

得分: 0

以下是翻译好的内容:

这是一个示例,展示了如何完成这个任务:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type TimeAndValue struct {
  6. time int64
  7. value float64
  8. }
  9. func main() {
  10. times := []int64{0, 1, 2, 3, 4}
  11. values := []float64{1.23, 2.34, 3.45, 4.56, 5.67}
  12. timesAndValues := zip(times, values)
  13. fmt.Println(timesAndValues)
  14. }
  15. func zip(ts []int64, vs []float64) []TimeAndValue {
  16. if len(ts) != len(vs) {
  17. panic("not same length")
  18. }
  19. var res []TimeAndValue
  20. for i, t := range ts {
  21. res = append(res, TimeAndValue{time: t, value: vs[i]})
  22. }
  23. return res
  24. }

链接:https://play.golang.org/p/1OWJ1HG1XL

英文:

Here's an example of how it can be done:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. type TimeAndValue struct {
  6. time int64
  7. value float64
  8. }
  9. func main() {
  10. times := []int64{0, 1, 2, 3, 4}
  11. values := []float64{1.23, 2.34, 3.45, 4.56, 5.67}
  12. timesAndValues := zip(times, values)
  13. fmt.Println(timesAndValues)
  14. }
  15. func zip(ts []int64, vs []float64) []TimeAndValue {
  16. if len(ts) != len(vs) {
  17. panic(&quot;not same length&quot;)
  18. }
  19. var res []TimeAndValue
  20. for i, t := range ts {
  21. res = append(res, TimeAndValue{time: t, value: vs[i]})
  22. }
  23. return res
  24. }

https://play.golang.org/p/1OWJ1HG1XL

huangapple
  • 本文由 发表于 2017年5月6日 09:55:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/43815912.html
匿名

发表评论

匿名网友

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

确定