可以使用sort.Slice()函数对每个切片进行排序,然后再进行比较。
示例代码:
package main
import (
"fmt"
"sort"
)
type NestedSlice [][]int
func (ns NestedSlice) Len() int {
return len(ns)
}
func (ns NestedSlice) Swap(i, j int) {
ns[i], ns[j] = ns[j], ns[i]
}
func (ns NestedSlice) Less(i, j int) bool {
sort.Slice(ns[i], func(k, l int) bool {
return ns[i][k] < ns[i][l]
})
sort.Slice(ns[j], func(k, l int) bool {
return ns[j][k] < ns[j][l]
})
return fmt.Sprintf("%v", ns[i]) < fmt.Sprintf("%v", ns[j])
}
func main() {
ns1 := NestedSlice{{1, 2, 3}, {4, 5}, {6, 7, 8}}
ns2 := NestedSlice{{2, 1, 3}, {5, 4}, {8, 6, 7}}
sort.Sort(ns1)
sort.Sort(ns2)
fmt.Println(ns1)
fmt.Println(ns2)
if fmt.Sprintf("%v", ns1) == fmt.Sprintf("%v", ns2) {
fmt.Println("The nested slices are equal")
} else {
fmt.Println("The nested slices are not equal")
}
}
输出结果:
[[1 2 3] [4 5] [6 7 8]]
[[1 2 3] [4 5] [6 7 8]]
The nested slices are equal
上一篇:比较嵌套列表中的值
下一篇:比较嵌套数组和另一个数组