对字符串切片进行排序:按字母顺序*在*降序后的字母

给定:


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"]


对所有东西都很新,谢谢你的任何提示


交互式爱情
浏览 117回答 1
1回答

SMILET

https://play.golang.org/p/hS4bo1q2tQlsort.Slice(alphanumeric, func(i, j int) bool {&nbsp; &nbsp; // check if we have numbers, sort them accordingly&nbsp;&nbsp; &nbsp; if z, err := strconv.Atoi(alphanumeric[i]); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; if y, err := strconv.Atoi(alphanumeric[j]); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; return y < z&nbsp; &nbsp; }&nbsp; &nbsp; // if we get only one number, alway say its greater than letter&nbsp;&nbsp; &nbsp; return true&nbsp; &nbsp; }&nbsp; &nbsp; // compare letters normally&nbsp;&nbsp; &nbsp; return alphanumeric[j] > alphanumeric[i]})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go