golang的sort函数不能对字符串切片进行排序。

huangapple go评论91阅读模式
英文:

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]) &lt; strings.ToLower(keys[j]) })

Link: https://stackoverflow.com/a/51997907/1626977

答案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

huangapple
  • 本文由 发表于 2023年7月20日 00:18:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76723341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定