golang defining dict like python with and appending value to list in dict

huangapple go评论92阅读模式
英文:

golang defining dict like python with and appending value to list in dict

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,尝试实现类似Python的嵌套结构,如下所示。我无法在Go中定义一个可以包含特定结构/类对象列表的空字典/映射,并且在遍历数据时无法向字典/映射中添加项目...非常感谢任何帮助...谢谢

items := []struct {
    item string
    obj  someObj
}{
    {"item1", someObj1},
    {"item2", someObj2},
    {"item3", someObj3},
    {"item3", someObj5},
    {"item1", someObj4},
}

rectors := make(map[string][]someObj)
for _, item := range items {
    if _, ok := rectors[item.item]; ok {
        rectors[item.item] = append(rectors[item.item], item.obj)
    } else {
        rectors[item.item] = []someObj{item.obj}
    }
}

fmt.Println(rectors)
// 输出: map[item2:[someObj2] item3:[someObj3 someObj5] item1:[someObj1 someObj4]]

以上是将Python代码转换为Go代码的结果,实现了类似的功能。希望对你有帮助!

英文:

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

得分: 2

这不是非常干净的代码,但它大致实现了你想要的,并且应该能帮助你朝正确的方向前进:

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)
}

输出结果:

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

主要的区别在于,你不能在初始化映射时同时修改已存在键的项(就像你在示例中对item1进行追加一样)。因此,在映射初始化之后,需要进行额外的步骤。你可以直接这样做:

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

但这似乎与你的操作不同。

在 Go Playground 上查看代码

英文:

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>

huangapple
  • 本文由 发表于 2015年2月20日 18:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/28626382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定