dqz84361326 2018-07-26 16:00 采纳率: 0%
浏览 2342
已采纳

在golang中循环遍历数组对象和分组的最佳方法

I have a list of Books (BookId) and each book is associated to a Book collection (CollectionId).

I am trying to figure out the best way to group the results by Collection, so all the books that belong to a collection are listed under it and I can build the results in the following way:

Book A,D,G belong to Collection 1. Book B,C,E belong to Collection 2.

I have the books in a list/array that I need to loop through and look up the collectionID they belong to and them need to store the new lists as seen below:

CollectionID 1:

- Book A, Book D, Book G

CollectionID 2:

- Book B, Book C, Book E

CollectionID 3:

- Book F
  • 写回答

2条回答 默认 最新

  • dongque1462 2018-07-26 16:35
    关注

    You can use a map to store a slice of books per collection ID.

    type Book struct {
        Title        string
        Author       string
        CollectionID int
    }
    
    func main() {
        books := GetBooks()
        collections := make(map[int][]Book)
        for _, b := range books {
            collections[b.CollectionID] = append(collections[b.CollectionID], b)
        }
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记