duanre4421 2019-04-04 10:38
浏览 140
已采纳

如何通过通道获取多个map [string] int并将它们合并为一张地图?

I am implementing a function that counts words and I am trying to write this with goroutines. So far I have made []string arrays to suitable sizes of the original string text and I send these to a goroutine each to count the words and add them to k/v pair inside a map[string]int, then I want to take them all through my channel and read all of the maps and simply count how many words in total there has been and return this map[string]int, but this is where I am lost. I tried to do something like

mapSummary := make(map[string]int)
for k, v := range channel {
    mapSummary[k] += v
}

but this does not work since I am using two variables in the range, and with only one I am not sure how to do this. So how do I add all of these maps together that I sent through a channel? I dont need you guys to show me exactly how this is done (it is a homework assignment) but since I did not recieve any help from my TAs in our labsession I would greatly appreciate some clues as to how this should be done, I also see that how I distribute the []string array is not good, but that I will figure out myself! :) This code does not include the main function or a majority of the code, but the necessary parts that I hope help you understand it.

ch := make(chan map[string]int)
for i := 0; i < 8; i++ {
    wg.Add(1)
    words := text[i*(len(text)/8):(i+1)*(len(text)/8)]
    go count(words, ch, wg)
}
wg.Wait()

mapSummary := make(map[string]int)
for k, v := range ch {
    mapSummary[k] += v
}
return mapSummary

func count(words []string, ch chan<- map[string]int, wg *sync.WaitGroup) {
    freqs := make(map[string]int)
    for _, word := range words {
        freqs[word] += 1
    }
    wg.Done()
    ch <- freqs
}

it tells me "too many variables in range".

  • 写回答

1条回答 默认 最新

  • dongye1912 2019-04-04 10:53
    关注

    If I use for k, v := range channel it tells me to many variables in range

    That's because a channel is only a list of values, there is no key. So do this:

    for val := range channel {
        // ..
    }
    

    Now val will be one of your maps, each time through the loop, so you'll probably want to range over that, too:

    for val := range channel {
        for k, v := range val {
            // Put your aggregation logic here
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路