How do I sort a slice of slices of something (how do I compare two slices) in Go

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

How do I sort a slice of slices of something (how do I compare two slices) in Go

问题

在Go语言中,可以比较两个字符串:

package main

func main() {
    println("ab" > "ba")
    println("ab" < "ba")
}
false
true

程序已退出。

链接:https://go.dev/play/p/svkLf6R84SC

我如何对两个切片执行类似的操作?例如 []int{1,2} > []int{2,1}

我需要这样做来对一个切片的切片进行排序。所以我需要一个 sort.Interface 的实现。

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

最好这个实现是通用的。

英文:

In Go is possible to compare two strings:

package main

func main() {
	println(&quot;ab&quot; &gt; &quot;ba&quot;)
	println(&quot;ab&quot; &lt; &quot;ba&quot;)
}
false
true

Program exited.

https://go.dev/play/p/svkLf6R84SC

How do I perform a similar operation on two slices? e.g. []int{1,2} &gt; []int{2,1}.

I need this to sort a slice of slices of ints. So I need an implementation of sort.Interface.

type Interface interface {
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
}

It would be better if this implementation is generic.

答案1

得分: 6

在标准库中,编写一个比较器和一个用于sort.Slices的less函数将是最有效的方法。稍微超出标准库的范围(直到标准库内的泛型用法最终确定),在Go 1.18中,我们可以使用golang.org/x/exp/constraintsgolang.org/x/exp/slices包来对一个包含有序值的切片进行泛型排序:https://go.dev/play/p/MA0lY6POVFR

func SortSlices[T constraints.Ordered](s [][]T) {
	sort.Slice(s, func(i, j int) bool {
		return slices.Compare(s[i], s[j]) < 0
	})
}

关于slices.Compare的文档:slices.Compare

Compare比较s1和s2的元素。元素按顺序逐个比较,从索引0开始,直到找到一个不相等的元素。返回比较第一个不匹配元素的结果。如果两个切片在其中一个结束之前都相等,则较短的切片被认为小于较长的切片。如果s1 == s2,则结果为0;如果s1 < s2,则结果为-1;如果s1 > s2,则结果为+1。比较中涉及到浮点数NaN的情况将被忽略。

英文:

Writing a comparator and a less function for sort.Slices would be the most effective way to do this within the standard library.
Stepping outside of that slightly (until generics usage within the standard library is finalized), in Go 1.18 we can use the golang.org/x/exp/constraints and golang.org/x/exp/slices packages to generically sort a slice of slices of ordered values: https://go.dev/play/p/MA0lY6POVFR

func SortSlices[T constraints.Ordered](s [][]T) {
	sort.Slice(s, func(i, j int) bool {
		return slices.Compare(s[i], s[j]) &lt; 0
	})
}

Documentation about slices.Compare:

> Compare compares the elements of s1 and s2. The elements are compared sequentially, starting at index 0, until one element is not equal to the other. The result of comparing the first non-matching elements is returned. If both slices are equal until one of them ends, the shorter slice is considered less than the longer one. The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2. Comparisons involving floating point NaNs are ignored.

huangapple
  • 本文由 发表于 2022年6月9日 20:47:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/72560564.html
匿名

发表评论

匿名网友

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

确定