简体   繁体   English

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

[英]Golang Split 2 dimensional array into multiple arrays of a single dimension

I have an array of two dimensions, how do I, out of that, make multiple arrays with a single dimension?我有一个二维数组,我如何从中创建多个具有单一维度的数组?

I need separate arrays as I need to pass an array with a single dimension to another function.我需要单独的数组,因为我需要将具有单一维度的数组传递给另一个函数。

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)

how do I ... make multiple arrays with a single dimension?我如何...制作具有单一维度的多个数组?


For your example,对于你的例子,

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游乐场: https : //play.golang.org/p/ETazZl1a-2F

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM