草庐IT

dictionary - 戈朗 : group and sum slice of structs

coder 2023-06-26 原文

我来自 .NET 世界,在那里我有 LINQ,所以我可以执行内存中查询,就像我们通常在 SQL 中看到的那样。

我有这个结构的一部分,我想按 8 个字段分组,然后对另一个整数字段求和。像这样的东西:

type Register struct {
    id1 int
    id2 int
    id3 int
    id4 int
    id5 int
    id6 int
    id7 int
    id8 int
    money int
}

我认为:

  • 创建一个 Equal 函数,比较结构(那八个
    字段)。 遍历我正在分析的集合。对于每个项目
    检查它是否已经在哈希表中。如果它在那里 => 我求和 场。如果不是 => 我将新项目添加到哈希表中。

有没有更好的方法或者任何美观、高效且易于使用的方法 图书馆?

最佳答案

基本上您的 idXX 字段是键,一个 n 元组。而money字段就是要求和的数据。

如果您稍微重构您的类型,这可以很容易地完成。仅将键放入结构中,因此它可以用作映射中的键。结构值为 comparable :

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

所以新类型:

type Key struct {
    id1 int
    id2 int
    id3 int
    id4 int
    id5 int
    id6 int
    id7 int
    id8 int
}

type Register struct {
    key   Key
    money int
}

为了分组和计算总和,您可以使用 map[Key]int,使用 Register.key 作为映射键来“分组”所有寄存器相同的键(相同的 ID):

regs := []*Register{
    {Key{id1: 345}, 1500},
    {Key{id1: 345, id2: 140}, 2700},
    {Key{id1: 345, id2: 140}, 1300},
    {Key{id1: 345}, 1000},
    {Key{id3: 999}, 1000},
    {Key{id3: 999}, 2000},
}

// calculate sum:
m := map[Key]int{}
for _, v := range regs {
    m[v.key] += v.money
}

fmt.Println(m)

输出:

map[{345 0 0 0 0 0 0 0}:2500 {345 140 0 0 0 0 0 0}:4000 {0 0 999 0 0 0 0 0}:3000]

为了一个好的输出:

fmt.Println("Nice output:")
for k, v := range m {
    fmt.Printf("%+3v: %d\n", k, v)
}

输出:

Nice output:
{id1:345 id2:  0 id3:  0 id4:  0 id5:  0 id6:  0 id7:  0 id8:  0}: 2500
{id1:345 id2:140 id3:  0 id4:  0 id5:  0 id6:  0 id7:  0 id8:  0}: 4000
{id1:  0 id2:  0 id3:999 id4:  0 id5:  0 id6:  0 id7:  0 id8:  0}: 3000

这是尽可能简单和高效的。试试 Go Playground 上的例子.

注意事项:

在 map 中,我们不必检查 Key 是否已经在其中。这是因为索引 map 会产生 zero value如果键不在 map 中,则返回 map 的值类型。所以在这种情况下,如果 Key 还不在 map 中,m[key] 会给你 0 (0int 类型的零值),正确地表明该键的“先前”总和到目前为止是 0

另请注意,Key 可能是 embedded fieldRegister 而不是“常规”字段中,没关系,这样你就可以引用 idXX 字段,就好像它们是 的一部分一样注册

关于dictionary - 戈朗 : group and sum slice of structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987023/

有关dictionary - 戈朗 : group and sum slice of structs的更多相关文章

  1. ruby - 在 OSX 上以编程方式使用 Dictionary.app 的词库功能(最好通过 Ruby) - 2

    我需要编写一个Ruby方法,它接受一个词,通过OS10.5的Dictionary.app的同义词库函数运行它,并返回备选词。如果Ruby方法最终调用命令行,那很好;我只需要能够从Ruby以编程方式完成它。查看RubyOSA后,我意识到可以通过某些词典服务访问词典[http://discussions.apple.com/thread.jspa?threadID=1561332],但我真的不明白。有人看到一个简单的解决方案吗?我也准备制作一个Automator工作流程并从命令行调用它,但由于某种原因我无法从shell中正确地为“获取定义”函数提供一个词(它一直说它不能'找到这个词,但是当

  2. javascript相当于python的dictionary.get - 2

    我正在尝试使用node.js验证JSON对象。基本上,如果存在条件A,那么我想确保某个特定值位于可能不存在的数组中。我在python中使用dictionary.get执行此操作,因为如果我查找不存在的内容,它将返回默认值。这是它在python中的样子ifoutput.get('conditionA')andnot'conditionB'inoutput.get('deeply',{}).get('nested',{}).get('array',[]):print"Thereisanerrorsomewhereyouneedtobefixing."我想为javascript找到类似的技术

  3. c# - 使用 JSON.net 序列化 Dictionary<int,object>? - 2

    我正在尝试使用JSON.net来序列化字典。使用JsonConvert.SerializeObject(theDict);这是我的结果{"1":{"Blah1":false,"Blah2":false,"Blah3":"None","Blah4":false},"2":{"Blah1":false,"Blah2":false,"Blah3":"None","Blah4":false},"3":{"Blah1":false,"Blah2":false,"Blah3":"None","Blah4":false},.........}有没有办法序列化这个字典,以便将键呈现为有效的javasc

  4. 已解决ValueError: dictionary update sequence element #0 has length 1; 2 is required - 2

    已解决ValueError:dictionaryupdatesequenceelement#0haslength1;2isrequired文章目录报错问题报错翻译报错内容解决方法千人全栈VIP答疑群联系博主帮忙解决报错报错问题粉丝群里面的一个小伙伴,想用Python爬虫然后解析数据,但是发生了报错(当时他心里瞬间凉了一大截,跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决的小伙伴),报错代码如下所示:defspider(page=1):""":parampage::return:"""url="http://www.ceic.ac.cn/ajax/sea

  5. dictionary - 如何将 map 转换为条目 slice ? - 2

    我正在尝试将键值映射转换为成对slice,例如给定如下映射:m:=make(map[int64]int64)m[521]=4m[528]=8我如何将其转换成其条目的一部分,例如:[[521,4],[528,8]]我正在考虑遍历所有这些键值然后为其创建slice,但是是否有任何简单的代码可以做到这一点? 最佳答案 packagemainimport"fmt"funcmain(){//createamapm:=map[int64]int64{512:8,513:9,234:9,392:0}//createaslicetoholdrequ

  6. 戈朗 "Log in to the site and download the xls file"? - 2

    关闭。这个问题需要更多focused.它目前不接受答案。想改进这个问题吗?更新问题,使其只关注一个问题editingthispost.关闭3年前。Improvethisquestion告诉我如何使用Golang登录网站。下载xls文件是得到了,但是为了在Excel表格中有数据,需要登录网站。该站点位于公司的服务器上。如果你能告诉你怎么做。例如,我用来执行此操作的VBA代码。SetoFields=CreateObject("Scripting.Dictionary")WithoFields.Add"login","sdiscor".Add"password","sdiscor"EndWi

  7. arrays - 戈朗 : Could not understand how below code is executing - 2

    下面是我查询的代码:我有一个单维数组a当我打印a[0][0]时,我不明白为什么它返回字符a的ascii值:packagemainimport("fmt")funcmain(){a:=[3]string{"a","b","c"}fmt.Println(a[0][0])}输出:97 最佳答案 下面是如何打印ascii的代码示例a:=[3]string{"a","b","c"}for_,rune:=rangea{fmt.Println(rune)//Itwillprinta,b,c}因为你在你的代码中使用了[0][0],所以它是等价的fo

  8. dictionary - 如何将具有嵌套对象的复杂 json 字符串转换为在 golang 中映射? - 2

    我有一个复杂的json格式字符串,我想将其转换为golang中的map。假设字符串是species:{"type":"human""age":"23""attributes":{"height":"182""weight":"160""contact":{"address":########"phone":#########}}}我如何解析它使得map[attributes]又是一个map[string]接口(interface)等等? 最佳答案 您可以使用map[string]interface{},例如:species:=mak

  9. dictionary - 从 map[string]string 获取单个键值 - 2

    我的cookie中存储了一张map,如下所示:cookieData:=map[expiration:1533455712ip:[hash:dd363d13234566727743277e96email:user@user.com]fmt.Println(reflect.TypeOf(cookie))>>map[string]string有人可以帮助我了解如何从这张map中只获取电子邮件值吗?提前致谢。 最佳答案 golang中的类型转换是通过附加.(T)完成的ip:=cookieData["ip"].(map[string]stri

  10. 戈朗 :which way is more efficient about using "for range" - 2

    typepath[]bytefunc(ppath)ToUpper(){fori,b:=rangep{if'a'在上面(这个例子是从“TheGoBlog”复制过来的),如果ToUpper变成这样:func(ppath)ToUpper(){fori,_:=rangep{if'a'哪个会更有效率为什么?“TheGoBlog”对前一个说:“这里的ToUpper方法在forrange构造中使用两个变量来捕获索引和slice元素。这种形式的循环避免了在主体中多次写入p[i]。”什么意思? 最佳答案 前者有更多的内存操作,即在b上:它在循环的第一

随机推荐