duanchen7401 2019-06-27 20:28
浏览 23
已采纳

从字符串值更新map [string] int [关闭]

I am trying to parse a json-like string which looks like this.

"abc:9, bar:3"

What I would like to have at the end is a map[string]int which looks like this:

map[string]int{"abc":9, "bar":3}

I have gotten as far as splitting it into a set of 'pairs', like so:

`["abc:9", "bar:3"]

I am struggling with how to get that structure into the final map[string]int. I have tried ranging over the slice, but I am missing how to actually get it into the map.

        val := "abc:9, bar:3"
        lsd := make(map[string]int)
        c := strings.Split(val, ",")
        for k, v := range c {
            lsd = v[k] // where I am struggling, I know this is wrong, but I can't seem to find the proper syntax and tools for this
        }

Can anyone point me in the right direction to end up with the map[string]int I am looking for here?

  • 写回答

1条回答 默认 最新

  • dounabi6295 2019-06-27 21:16
    关注

    This is a tiny bit cheesy but I was having trouble making fmt.Sscanf grok the pattern, so I am just splitting again. And you may have been missing strconv - strconv.Atoi is a quick converter.

    package main
    
    import (
        "fmt"
        "strconv"
        "strings"
    )
    
    func main() {
        lsd := make(map[string]int)
        toParse := "abc:5, foo:5"
        parts := strings.Split(toParse, ", ")
        for _, p := range parts {
    
            results := strings.SplitN(p, ":", 2)
            val, err := strconv.Atoi(results[1])
            if err != nil {
                panic(err)  //probably want to do somethig better
            }
            lsd[results[0]] = val
        }
    
        fmt.Printf("%#v", lsd)
    }
    

    map[string]int{"abc":5, "foo":5}

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大