sorting - How one can do case insensitive sorting using sort.Strings() in Golang?
问题描述
Is there any way to pass the custom function in the sort.Strings() to do the case-insensitive sorting on the list of strings?
data := []string{"A", "b", "D", "c"}
The output should be: A, b, c, D
The equivalent of the above requirement in Python is like :
li = sorted(data, key=lambda s: s.lower())
Do we have something like that in golang?
解决方案
The translation of the Python code to Go is:
sort.Slice(data, func(i, j int) bool { return strings.ToLower(data[i]) < strings.ToLower(data[j]) })
This approach, like the Python code in the question, can allocate two strings for each comparison. The allocations are probably OK for the example in the question, but can be a problem in other scenarios.
To avoid allocations, compare the strings rune by rune:
func lessLower(sa, sb string) bool {
for {
rb, nb := utf8.DecodeRuneInString(sb)
if nb == 0 {
// The number of runes in sa is greater than or
// equal to the number of runes in sb. It follows
// that sa is not less than sb.
return false
}
ra, na := utf8.DecodeRuneInString(sa)
if na == 0 {
// The number of runes in sa is less than the
// number of runes in sb. It follows that sa
// is less than sb.
return true
}
rb = unicode.ToLower(rb)
ra = unicode.ToLower(ra)
if ra != rb {
return ra < rb
}
// Trim rune from the beginning of each string.
sa = sa[na:]
sb = sb[nb:]
}
}
⋮
sort.Slice(data, func(i, j int) bool { return lessLower(data[i], data[j]) })
Take a look at the collate package if you need to sort by language or culture specific sort orders.
推荐阅读
- python - Heroku Django 应用程序错误:gunicorn.errors.HaltServer:
- wireshark-dissector - 自定义wireshark运行时看不到编译好的插件?
- excel - objConnectionVS.Execute 做什么以及是否有相同功能的替代品
- angular - 删除 jhi-page-ribbon 会破坏 loginService 上的 accountService 注入
- javascript - 下一个 js 中的 HTTPS 重定向
- google-apps-script - 在电子表格 onOpen 中包含父文件夹名称
- .htaccess - .htaccess 中的 RewriteRule 语法不起作用
- postgresql - 跟踪长时间运行的函数(从外部)进度的最佳方法 - PostgreSQL 11?
- python-3.x - 系统找不到指定的路径:我是否可以通过调整导入的模块变量、设置环境变量等来修复?
- gremlin - Gremlin:根据两个属性值的比较选择顶点