dsy48837 2015-02-20 10:10
浏览 403
已采纳

golang定义dict像python一样,并在dict中将值附加到列表中

I am new to go and trying to implement python like nested structure as below, I am not able to define the empty dict/map in golang that can have list of specific struct/classobj and while iterating through the data I am not able to append items in map/dict ... I will really appreciate any help on this ... Thanks

items = [
    ("item1", someObj1),
    ("item2", someObj2),
    ("item3", someObj3),
    ("item3", someObj5),
    ("item1", someObj4),
]

rectors = {}
for item, obj in items:
    try:
        rectors[item].append(obj)
    except KeyError:
        rectors[item] = [obj]

print rectors
# OUTPUT: {'item2': [someObj2], 'item3': [someObj3, someObj5], 'item1': [someObj1, someObj4]}
  • 写回答

1条回答 默认 最新

  • dpba63888 2015-02-20 10:45
    关注

    Its not quite as clean .. but this does roughly what you want and should get you started on the right path:

    type someObj struct {
    }
    
    func main() {
        items := map[string][]someObj{
            "item1": []someObj{someObj{}},
            "item2": []someObj{someObj{}},
            "item3": []someObj{someObj{}},
        }
    
        items["item1"] = append(items["item1"], someObj{})
    
        rectors := make(map[string][]someObj)    
    
        for key, val := range items {
            if obj, exists := rectors[key]; exists {
                rectors[key] = append(obj, val...)
            } else {
                rectors[key] = val
            }
        }
    
        fmt.Printf("%v", rectors)
    }
    

    Output:

    map[item3:[{}] item1:[{} {}] item2:[{}]]
    

    The main difference being .. you can't initialize the map and alter an item with a key that already exists (as you appear to be doing in your example with item1 being appended during initialization). So that becomes an extra step after the initialization of the map. You could always just do:

    "item1": []someObj{someObj{}, someObj{}},
    

    .. but that didn't seem to be the same as what you were doing.

    <kbd>See it on the Go playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog