对字符串切片进行排序:字母按字母顺序*在*降序数字之后
sort a string slice: letters in alphabetical order *after* descending numbers
给定:
alphanumeric := ["aaa","bbb","ccc","111","222","333"]
排序后:
["333","222","111","aaa","bbb","ccc"]
尝试内置排序包:
sort.Strings(alphanumeric)
很接近,但数字部分将按升序排列
["111","222","333","aaa","bbb","ccc"]
还有:
sort.Slice(alphanumeric, func(i, j int) bool {
return alphanumeric[i] > alphanumeric[j]
})
结果是不需要的:["ccc","bbb","aaa","333","222","111"]
对所有东西都很陌生,感谢您的任何提示
https://play.golang.org/p/hS4bo1q2tQl
sort.Slice(alphanumeric, func(i, j int) bool {
// check if we have numbers, sort them accordingly
if z, err := strconv.Atoi(alphanumeric[i]); err == nil {
if y, err := strconv.Atoi(alphanumeric[j]); err == nil {
return y < z
}
// if we get only one number, alway say its greater than letter
return true
}
// compare letters normally
return alphanumeric[j] > alphanumeric[i]
})
给定:
alphanumeric := ["aaa","bbb","ccc","111","222","333"]
排序后:
["333","222","111","aaa","bbb","ccc"]
尝试内置排序包:
sort.Strings(alphanumeric)
很接近,但数字部分将按升序排列
["111","222","333","aaa","bbb","ccc"]
还有:
sort.Slice(alphanumeric, func(i, j int) bool {
return alphanumeric[i] > alphanumeric[j]
})
结果是不需要的:["ccc","bbb","aaa","333","222","111"]
对所有东西都很陌生,感谢您的任何提示
https://play.golang.org/p/hS4bo1q2tQl
sort.Slice(alphanumeric, func(i, j int) bool {
// check if we have numbers, sort them accordingly
if z, err := strconv.Atoi(alphanumeric[i]); err == nil {
if y, err := strconv.Atoi(alphanumeric[j]); err == nil {
return y < z
}
// if we get only one number, alway say its greater than letter
return true
}
// compare letters normally
return alphanumeric[j] > alphanumeric[i]
})