Go 中的切片分块

问题描述 投票:0回答:9

我有一个切片,其中包含约 210 万个日志字符串,我想创建一个切片切片,其中字符串尽可能均匀分布。

这是我到目前为止所拥有的:

// logs is a slice with ~2.1 million strings in it.
var divided = make([][]string, 0)
NumCPU := runtime.NumCPU()
ChunkSize := len(logs) / NumCPU
for i := 0; i < NumCPU; i++ {
    temp := make([]string, 0)
    idx := i * ChunkSize
    end := i * ChunkSize + ChunkSize
    for x := range logs[idx:end] {
        temp = append(temp, logs[x])
    }
    if i == NumCPU {
        for x := range logs[idx:] {
            temp = append(temp, logs[x])
        }
    }
    divided = append(divided, temp)
}

idx := i * ChunkSize
将为我提供
logs
索引的当前“块开始”,而
end := i * ChunkSize + ChunkSize
将为我提供“块结束”,或该块范围的末尾。我找不到任何关于如何在 Go 中分块/分割切片或在有限范围内迭代的文档或示例,所以这就是我想到的。但是,它仅多次复制第一个块,因此不起作用。

如何(尽可能均匀地)在 Go 中对切片进行分块?

go slice chunking
9个回答
106
投票

您不需要制作新切片,只需将

logs
切片附加到
divided
切片即可。

http://play.golang.org/p/vyihJZlDVy

var divided [][]string

chunkSize := (len(logs) + numCPU - 1) / numCPU

for i := 0; i < len(logs); i += chunkSize {
    end := i + chunkSize

    if end > len(logs) {
        end = len(logs)
    }

    divided = append(divided, logs[i:end])
}

fmt.Printf("%#v\n", divided)

20
投票

使用泛型(Go 版本 >=1.18):

func chunkBy[T any](items []T, chunkSize int) (chunks [][]T) {
    for chunkSize < len(items) {
        items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])
    }
    return append(chunks, items)
}

游乐场网址

或者如果您想手动设置容量:

func chunkBy[T any](items []T, chunkSize int) [][]T {
    var _chunks = make([][]T, 0, (len(items)/chunkSize)+1)
    for chunkSize < len(items) {
        items, _chunks = items[chunkSize:], append(_chunks, items[0:chunkSize:chunkSize])
    }
    return append(_chunks, items)
}

游乐场网址


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(actions) {
    actions, batches = actions[batchSize:], append(batches, actions[0:batchSize:batchSize])
}
batches = append(batches, actions)

产生以下结果:

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

6
投票

另一种变体。它的工作速度比 JimB 提出的快约 2.5 倍。测试和基准测试位于此处

https://play.golang.org/p/WoXHqGjozMI

func chunks(xs []string, chunkSize int) [][]string {
    if len(xs) == 0 {
        return nil
    }
    divided := make([][]string, (len(xs)+chunkSize-1)/chunkSize)
    prev := 0
    i := 0
    till := len(xs) - chunkSize
    for prev < till {
        next := prev + chunkSize
        divided[i] = xs[prev:next]
        prev = next
        i++
    }
    divided[i] = xs[prev:]
    return divided
}

1
投票
func chunkSlice(items []int32, chunkSize int32) (chunks [][]int32) {
 //While there are more items remaining than chunkSize...
 for chunkSize < int32(len(items)) {
    //We take a slice of size chunkSize from the items array and append it to the new array
    chunks = append(chunks, items[0:chunkSize])
    //Then we remove those elements from the items array
    items = items[chunkSize:]
 }
 //Finally we append the remaining items to the new array and return it
 return append(chunks, items)
}

视觉示例

假设我们想将一个数组分成 3 个块

items:  [1,2,3,4,5,6,7]
chunks: []

items:  [1,2,3,4,5,6,7]
chunks: [[1,2,3]]

items:  [4,5,6,7]
chunks: [[1,2,3]]

items:  [4,5,6,7]
chunks: [[1,2,3],[4,5,6]]

items:  [7]
chunks: [[1,2,3],[4,5,6]]

items:  [7]
chunks: [[1,2,3],[4,5,6],[7]]
return

0
投票

对任何 []T 使用反射

https://github.com/kirito41dd/xslice

package main

import (
    "fmt"
    "github.com/kirito41dd/xslice"
)

func main() {
    s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    i := xslice.SplitToChunks(s, 3)
    ss := i.([][]int)
    fmt.Println(ss) // [[0 1 2] [3 4 5] [6 7 8] [9]]
}

https://github.com/kirito41dd/xslice/blob/e50d91fa75241a3a03d262ad51c8e4cb2ea4b995/split.go#L12

func SplitToChunks(slice interface{}, chunkSize int) interface{} {
    sliceType := reflect.TypeOf(slice)
    sliceVal := reflect.ValueOf(slice)
    length := sliceVal.Len()
    if sliceType.Kind() != reflect.Slice {
        panic("parameter must be []T")
    }
    n := 0
    if length%chunkSize > 0 {
        n = 1
    }
    SST := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, length/chunkSize+n)
    st, ed := 0, 0
    for st < length {
        ed = st + chunkSize
        if ed > length {
            ed = length
        }
        SST = reflect.Append(SST, sliceVal.Slice(st, ed))
        st = ed
    }
    return SST.Interface()
}

0
投票

总结:

// ChunkStringSlice divides []string into chunks of chunkSize.
func ChunkStringSlice(s []string, chunkSize int) [][]string {
    chunkNum := int(math.Ceil(float64(len(s)) / float64(chunkSize)))
    res := make([][]string, 0, chunkNum)
    for i := 0; i < chunkNum-1; i++ {
        res = append(res, s[i*chunkSize:(i+1)*chunkSize])
    }
    res = append(res, s[(chunkNum-1)*chunkSize:])
    return res
}

// ChunkStringSlice2 divides []string into chunkNum chunks.
func ChunkStringSlice2(s []string, chunkNum int) [][]string {
    res := make([][]string, 0, chunkNum)
    chunkSize := int(math.Ceil(float64(len(s)) / float64(chunkNum)))
    for i := 0; i < chunkNum-1; i++ {
        res = append(res, s[i*chunkSize:(i+1)*chunkSize])
    }
    res = append(res, s[(chunkNum-1)*chunkSize:])
    return res
}

0
投票

go-deeper/chunks 模块,允许将任何类型的切片(带有泛型)分割成大约等于值总和的块。

package main

import (
    "fmt"

    "github.com/go-deeper/chunks"
)

func main() {
    slice := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sliceChunks := chunks.Split(slice, 7)

    fmt.Println(sliceChunks)
}

输出:

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

0
投票

Go 1.23(2024 年 8 月)

使用

slices.Chunk
。这给出了一个 迭代器,你可以在 :

范围内进行调整
import (
    "fmt"
    "slices"
)

func main() {
    vals := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

    for chunk := range slices.Chunk(vals, 2) {
        fmt.Println(chunk)
    }

}

打印:

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

游乐场:https://go.dev/play/p/NvPQg5CojCb?v=gotip

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.