Sorting 如何根据数值对切片排序,如果数值等于,则按字母顺序排序
我有下面的切片Sorting 如何根据数值对切片排序,如果数值等于,则按字母顺序排序,sorting,go,slice,Sorting,Go,Slice,我有下面的切片 {string, int } [{zaa 1} {aab 1} {xac 1}] 在这种情况下,int-side相等,所以我不需要按字母顺序排序 如果我的切片像吼叫 [{zaa 1} {aab 4} {xac 2}] 我需要使用数值进行排序,我如何才能做到这一点 现在我正在使用golang给出的排序 type ByStringValue []string type ByNumericValue []WeightBaseResourceInfo func (a ByStr
{string, int }
[{zaa 1} {aab 1} {xac 1}]
在这种情况下,int-side相等,所以我不需要按字母顺序排序
如果我的切片像吼叫
[{zaa 1} {aab 4} {xac 2}]
我需要使用数值进行排序,我如何才能做到这一点
现在我正在使用golang给出的排序
type ByStringValue []string
type ByNumericValue []WeightBaseResourceInfo
func (a ByStringValue) Len() int { return len(a) }
func (a ByStringValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByStringValue) Less(i, j int) bool { return a[i] < a[j] }
func (a ByNumericValue) Len() int { return len(a) }
func (a ByNumericValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByNumericValue) Less(i, j int) bool {
w1 := a[i].Weight
w2 := a[j].Weight
return w1 > w2
}
键入ByStringValue[]字符串
键入ByNumericValue[]WeightBaseResourceInfo
func(a ByStringValue)Len()int{return Len(a)}
func(a ByStringValue)Swap(i,j int){a[i],a[j]=a[j],a[i]}
func(a ByStringValue)减去(i,j int)bool{返回a[i]w2
}
对于排序切片,只需使用Go 1.8中添加的
要使用sort.Slice()
您只需要提供一个comparator函数,它必须告诉您一个元素是否小于另一个元素
less()
函数中的逻辑应首先测试数字,如果它们不同,则数字应决定结果。如果它们相等,则比较文本值以判断其中一个是否小于另一个
例如:
type Entry struct {
Text string
Number int
}
func main() {
es := []Entry{
{"zaa", 1}, {"aab", 1}, {"xac", 1},
{"zaa", 1}, {"aab", 4}, {"xac", 2},
}
sort.Slice(es, func(i, j int) bool {
if a, b := es[i].Number, es[j].Number; a != b {
return a < b
}
return es[i].Text < es[j].Text
})
fmt.Println(es)
}
键入ByName[]WeightBaseResourceInfo
func(a ByName)Len()int{return Len(a)}
func(a ByName)Swap(i,j int){a[i],a[j]=a[j],a[i]}
func(a ByName)Less(i,j int)bool{返回a[i].ResourceId
导入“反映”
[{aab 1} {xac 1} {zaa 1} {zaa 1} {xac 2} {aab 4}]
type ByName []WeightBaseResourceInfo
func (a ByName) Len() int { return len(a) }
func (a ByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByName) Less(i, j int) bool { return a[i].ResourceId < a[j].ResourceId }
func main() {
resourceWeightInfo := make([]WeightBaseResourceInfo, 3)
start := make([]WeightBaseResourceInfo, 3)
var tempWeightInfo WeightBaseResourceInfo
tempWeightInfo.ResourceId = "zaa"
tempWeightInfo.Weight = 2
resourceWeightInfo[0] = tempWeightInfo
tempWeightInfo.ResourceId = "aab"
tempWeightInfo.Weight = 5
resourceWeightInfo[1] = tempWeightInfo
tempWeightInfo.ResourceId = "xac"
tempWeightInfo.Weight = 1
resourceWeightInfo[2] = tempWeightInfo
copy(start,resourceWeightInfo)
fmt.Println("start", start)
sort.Sort(ByNumericValue(resourceWeightInfo))
if(reflect.DeepEqual(start,resourceWeightInfo)){
sort.Sort(ByName(resourceWeightInfo))
}
fmt.Println("Sorted", resourceWeightInfo)
}