Golang将二维数组拆分为多个一维数组[duplicate]

qybjjes1  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(155)

此问题在此处已有答案

Slice chunking in Go(8个答案)
7天前关闭。
我有一个二维数组,我如何从这个数组中,得到多个一维数组呢?
我需要单独的数组,因为我需要将一维数组传递给另一个函数。

actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
batchSize := 3
batches := make([][]int, 0, (len(actions)+batchSize-1)/batchSize)

for batchSize < len(protoFiles) {
    actions, batches = actions[batchSize:], append(batches, actions[0:batchSize:batchSize])
}
batches = append(batches, actions)
jdgnovmf

jdgnovmf1#

我该怎么......用一个维度来做多个数组呢?
对于您的示例,

package main

import "fmt"

func batchActions(a []int, c int) [][]int {
    r := (len(a) + c - 1) / c
    b := make([][]int, r)
    lo, hi := 0, c
    for i := range b {
        if hi > len(a) {
            hi = len(a)
        }
        b[i] = a[lo:hi:hi]
        lo, hi = hi, hi+c
    }
    return b
}

func main() {
    actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(actions)
    batchSize := 3
    batches := batchActions(actions, batchSize)
    fmt.Println(batchSize, batches)
}

Playground:https://play.golang.org/p/ETazZl1a-2F
输出量:

[0 1 2 3 4 5 6 7 8 9]
3 [[0 1 2] [3 4 5] [6 7 8] [9]]

相关问题