英文:
golang sort function does not sort string slice
问题
我有以下代码:
m := map[string][]string{
"LaptopPro": {"M1-pro", "M2"},
"Speaker": {"klipsch"},
"dev": {"ddd"},
"dv": {"ddd"},
"laptop": {"m1", "m2"},
"laptop99": {"m1", "m2"},
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, m[k])
}
但输出结果是:
LaptopPro [M1-pro M2]
Speaker [klipsch]
dev [ddd]
dv [ddd]
laptop [m1 m2]
laptop99 [m1 m2]
这显然没有排序。为什么会这样呢?
英文:
I have following code
m := map[string][]string{
"LaptopPro": {"M1-pro", "M2"},
"Speaker": {"klipsch"},
"dev": {"ddd"},
"dv": {"ddd"},
"laptop": {"m1", "m2"},
"laptop99": {"m1", "m2"},
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, m[k])
}
But the output is:
LaptopPro [M1-pro M2]
Speaker [klipsch]
dev [ddd]
dv [ddd]
laptop [m1 m2]
laptop99 [m1 m2]
Which is definitely not sorted.Why is this happening?
答案1
得分: 3
如Burak所指出的,我想要不区分大小写的排序。我再次搜索包含“不区分大小写”短语的内容,这里是我找到的解决方案:
sort.Slice(keys, func(i, j int) bool { return strings.ToLower(keys[i]) < strings.ToLower(keys[j]) })
链接:https://stackoverflow.com/a/51997907/1626977
英文:
As Burak noted, I wanted case-insensitive sort. I searched again includeing case-insensitive
phrase and here's the solution I have found:
sort.Slice(keys, func(i, j int) bool { return strings.ToLower(keys[i]) < strings.ToLower(keys[j]) })
答案2
得分: 0
它确实做到了。
之前的键:
[laptop laptop99 LaptopPro Speaker dev dv]
之后的键:
LaptopPro [M1-pro M2]
Speaker [klipsch]
dev [ddd]
dv [ddd]
laptop [m1 m2]
laptop99 [m1 m2]
首先,Go会将大写字母排序,小写字母排在最后。
英文:
It did.
keys before:
[laptop laptop99 LaptopPro Speaker dev dv]
keys after:
LaptopPro [M1-pro M2]
Speaker [klipsch]
dev [ddd]
dv [ddd]
laptop [m1 m2]
laptop99 [m1 m2]
First Go will sort uppercase, and lowercase in the end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论