gpt4 book ai didi

dictionary - 如何将map[string]int切成 block

转载 作者:行者123 更新时间:2023-12-02 16:06:53 28 4
gpt4 key购买 nike

我的目标是获取可能包含多达一百万个条目的 map[string]int 并将其分成最多 500 个大小的 block ,并将 map POST 到外部服务。我是 golang 新手,所以现在正在 Go Playground 中进行修改。

Any tips anyone has on how to improve the efficiency of my code base, please share!

Playground :https://play.golang.org/p/eJ4_Pd9X91c

我看到的 CLI 输出是:

original size 60
chunk bookends 0 20
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
chunk bookends 20 40
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
chunk bookends 40 60
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,

这里的问题是,虽然正确计算了 block 书挡,但 x 值每次都从 0 开始。我想我应该期望它从 block 书尾最小值开始,即 0、20、40 等。为什么范围每次都从零开始?

来源:

package main

import (
"fmt"
"math/rand"
"strconv"
)

func main() {
items := make(map[string]int)

// Generate some fake data for our testing, in reality this could be 1m entries
for i := 0; i < 60; i ++ {
// int as strings are intentional here
items[strconv.FormatInt(int64(rand.Int()), 10)] = rand.Int()
}

// Create a map of just keys so we can easily chunk based on the numeric keys
i := 0
keys := make([]string, len(items))
for k := range items {
keys[i] = k
i++
}

fmt.Println("original size", len(keys))
//batchContents := make(map[string]int)

// Iterate numbers in the size batch we're looking for
chunkSize := 20
for chunkStart := 0; chunkStart < len(keys); chunkStart += chunkSize {
chunkEnd := chunkStart + chunkSize

if chunkEnd > len(items) {
chunkEnd = len(items)
}

// Iterate over the keys
fmt.Println("chunk bookends", chunkStart, chunkEnd)
for x := range keys[chunkStart:chunkEnd] {
fmt.Print(x, ",")

// Build the batch contents with the contents needed from items
// @todo is there a more efficient approach?
//batchContents[keys[i]] = items[keys[i]]
}
fmt.Println()

// @todo POST final batch contents
//fmt.Println(batchContents)
}

}

最佳答案

当你处理一个 block 时:

for x := range keys[chunkStart:chunkEnd] {}

您正在迭代一个 slice ,并且有一个迭代变量,它将是 slice 索引,而不是 slice 中的元素(在给定索引处)。因此它总是从 0 开始。 (当您迭代映射时,第一个迭代变量是键,因为那里没有索引,第二个迭代变量是与该键关联的值。)

相反,你想要这个:

for _, key := range keys[chunkStart:chunkEnd] {}

另请注意,首先将键收集到 slice 中,然后再处理它们是多余的。首先,您可以在迭代 map 一次时执行此操作。只需保留一个对迭代进行计数的变量即可知道何时达到 block 大小,如果您使用保留该大小的数据结构(例如键批处理 slice 的大小),则这可能是隐式的。

例如(在 Go Playground 上尝试一下):

chunkSize := 20
batchKeys := make([]string, 0, chunkSize)
process := func() {
fmt.Println("Batch keys:", batchKeys)
batchKeys = batchKeys[:0]
}

for k := range items {
batchKeys = append(batchKeys, k)
if len(batchKeys) == chunkSize {
process()
}
}
// Process last, potentially incomplete batch
if len(batchKeys) > 0 {
process()
}

关于dictionary - 如何将map[string]int切成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57871411/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com