将方法中的 2 个切片合并到映射中

Merging 2 slices from a method into a map

我有一个函数 returns 2 个切片形式的变量,我想将这两个切片合并到一个映射中作为键值对。问题是无法找到一种方法来分别遍历每个切片并将它们添加为键和值。 当前的实现是遍历所有价格,并将每个价格添加到城镇键。

package main

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

func main() {
    cities, prices := citiesAndPrices()
    towns := groupSlices(cities, prices)
    for cities := range towns {

        fmt.Println(cities, prices)
    }

}

func citiesAndPrices() ([]string, []int) {
    rand.Seed(time.Now().UnixMilli())
    cityChoices := []string{"Berlin", "Moscow", "Chicago", "Tokyo", "London"}
    dataPointCount := 100
    cities := make([]string, dataPointCount)
    for i := range cities {
        cities[i] = cityChoices[rand.Intn(len(cityChoices))]
    }
    prices := make([]int, dataPointCount) 
    for i := range prices {
        prices[i] = rand.Intn(100)
    }
    return cities, prices
}

func groupSlices([]string, []int) map[string]int {
    cities, prices := citiesAndPrices()
    towns := make(map[string]int)
    for _, cities := range cities {
        for _, prices := range prices {
            towns[cities] = prices
            break
        }
    }
    return towns
}

您必须 return groupSlice 函数作为 map[string][]int

这是给你的提示:

Seed, unlike the Rand.Seed method, is safe for concurrent use. source.

所以你可以调用一次,而不是每次调用函数。这将加快您的应用程序。

我认为这就是您想要的代码。

package main

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

func main() {
    rand.Seed(time.Now().UnixNano())
    cities, prices := citiesAndPrices()
    towns := groupSlices(cities, prices)
    fmt.Println()
    total := 0
    for c, p := range towns {
        fmt.Println(c, p)
        total += len(p)
    }
    fmt.Println()
    fmt.Println("total must 200, found :", total) // total must be 200
}

func citiesAndPrices() ([]string, []int) {
    cityChoices := []string{"Berlin", "Moscow", "Chicago", "Tokyo", "London"}
    dataPointCount := 100
    cities := make([]string, dataPointCount)
    prices := make([]int, dataPointCount)
    for i := range cities {
        cities[i] = cityChoices[rand.Intn(len(cityChoices))]
        prices[i] = rand.Intn(100)
    }
    fmt.Println("inside citiesAndPrices func")
    fmt.Println(cities)
    fmt.Println(prices)
    fmt.Println("done run citiesAndPrices func\n")
    return cities, prices
}

func groupSlices(c1 []string, p1 []int) map[string][]int {
    c2, p2 := citiesAndPrices()
    towns := make(map[string][]int)
    for i, t := range c1 {
        // this is for cities1 and price1
        if towns[t] == nil {
            towns[t] = make([]int, 0)
        }
        towns[t] = append(towns[t], p1[i])

        // this is for cities2 and price2
        if towns[c2[i]] == nil {
            towns[c2[i]] = make([]int, 0)
        }
        towns[c2[i]] = append(towns[c2[i]], p2[i])
    }
    return towns
}