我的数据是逐行创建的,6 列,我事先不知道最终的行数。
目前,我正在创建一个全为零的 200x6 二维 slice ,然后我逐行用我的数据逐渐替换这些零。数据来自另一个dataframe df
它有效,但我不喜欢我的 slice 的最后一行全是零。我看到 2 个解决方案: - 完成后我删除所有最后一行只有零 - 我创建了一个空 slice 并将我的数据逐步添加到它
我尝试了各种方法,但无法弄清楚如何对这两种解决方案中的任何一种进行编码。
目前我的代码是这样的:
var orders [200][6]float64 // create my 2d slice with zeros
order_line := 0
for i := start_line; i <= end_line; i++ {
if sell_signal == "1" {
//record line number and sold price in orders slice
orders[order_line][1] = float64(i+1)
orders[order_line][2],err = strconv.ParseFloat(df[i][11], 64)
order_line = order_line + 1
}
}
我查看了 Append 命令,但我尝试了各种组合以使其在 2d slice 上工作,但找不到有效的组合。
编辑:从下面的评论中我了解到我实际上是在创建一个数组,而不是一个 slice ,并且无法将数据 append 到数组。
最佳答案
在 Golang 中, slice 代替数组是首选。
不需要在 prior 中创建这么多行,只需在每次循环数据时创建一个 slice 以在父 slice 中添加一个新行。这将帮助您只拥有所需的行数,并且您需要担心长度,因为您要在父 slice 的索引处 append 一个 slice 。
package main
import (
"fmt"
"math/rand"
)
func main() {
orders := make([][]float64, 0) // create my 2d slice with zeros
for i := 0; i <= 6; i++ {
value := rand.Float64()
temp := make([]float64, 0)
temp = append(temp, value)
orders = append(orders, [][]float64{temp}...)
}
fmt.Println(orders)
}
请检查 Playground 上的工作代码
如果您注意到我在循环中创建一个新的 temp
slice ,其中包含 float64
值,然后将值 append 到我已传递给父 slice 的临时 slice .
所以每次我将临时 slice append 到父 slice 时,都会创建一个新行。
注意:
Arrays have their place, but they're a bit inflexible, so you don't see them too often in Go code. Slices, though, are everywhere. They build on arrays to provide great power and convenience.
已编辑:
处理前 3 列,然后操作接下来 3 列的值,这些值将添加到临时 slice 并 append 到主 slice 。使用以下代码逻辑:
package main
import (
"fmt"
"math/rand"
"strconv"
)
func main() {
orders := make([][]float64, 0) // create my 2d slice with zeros
for i := 0; i <= 6; i++ {
value := rand.Float64()
// logic to create first 3 columns
temp := make([]float64, 0)
temp = append(temp, value)
temp2 := make([]float64, 3)
// logic to create next 3 columns on basis of previous 3 columns
for j, value := range temp {
addcounter, _ := strconv.ParseFloat("1", 64)
temp2[j] = value + addcounter
}
temp = append(temp, temp2...)
orders = append(orders, [][]float64{temp}...)
}
fmt.Println(orders)
}
工作 Example
关于go - 如何 append 到二维 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52706495/