如何基于参数对对象列表进行分类 [英] How to categorize list of objects based on a parameter
问题描述
我有一个具有此定义的对象列表:
I have a list of objects with this definition:
type MyObject struct {
ID int `json:"id"`
Level int `json:"level"`
CityID int `json:"city_id"`
}
我想基于 CityID
对它们进行分类,以获取列表列表,其中每个内部列表的项目都具有相同的 CityID
.
I want to categorize them based on CityID
in order to get a list of lists where each inner list's items have the same CityID
.
例如,如果我有以下列表:
For example, if I have the following list:
[
MyObject {ID: 1, Level: 12, CityID: 7},
MyObject {ID: 2, Level: 15, CityID: 2},
MyObject {ID: 3, Level: 55, CityID: 4},
MyObject {ID: 4, Level: 88, CityID: 7},
MyObject {ID: 5, Level: 11, CityID: 4},
MyObject {ID: 6, Level: 5, CityID: 7},
MyObject {ID: 7, Level: 42, CityID: 2}
]
我需要下面的输出:
[
[MyObject {ID: 1, Level: 12, CityID: 7}, MyObject {ID: 4, Level: 88, CityID: 7}, MyObject {ID: 6, Level: 5, CityID: 7}],
[MyObject {ID: 2, Level: 15, CityID: 2}, MyObject {ID: 7, Level: 42, CityID: 2}],
[MyObject {ID: 3, Level: 55, CityID: 4}, MyObject {ID: 5, Level: 11, CityID: 4}]
]
我知道使用 itertools
在python中是可能的,但是我在 go
中是新手,对它的库知之甚少.有帮助吗?
I know it is possible in python using itertools
, but I'm new in go
and have little knowledge about its libraries. Any help?
我当前正在使用此
m := make(map[int][]MyObject)
for _, item := range myList {
if val, ok := m[item.CityID]; ok {
m[item.CityID] = append(val, item)
} else {
m[item.CityID] = []MyObject{item, }
}
}
推荐答案
您当前的方法是可行的方法,但是可以简化,无需检查 CityID
是否已经在地图中,因为索引带有未在其中的键的地图会导致值类型的零值,对于切片而言为 nil
,您可以毫无问题地附加到 nil
切片:
Your current approach is the way to go, but it may be simplified, there is no need to check if a CityID
is already in the map, because indexing a map with a key that isn't in it will result in the zero value of the value type, which is nil
for slices, and you may append to a nil
slice without a problem:
m := make(map[int][]MyObject)
for _, item := range myList {
m[item.CityID] = append(m[item.CityID], item)
}
这篇关于如何基于参数对对象列表进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!