如何对一个整数Go的片断进行排序? [英] How do I reverse sort a slice of integer Go?

查看:173
本文介绍了如何对一个整数Go的片断进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 例子:= [] int {1, 25,3,5,4} 
sort.Ints(example)//这会给我一个从1到最高数字的分片

我如何对它进行排序,使其从最高到最低?所以[25 5 4 3 1]



我试过这个

  sort.Sort(sort.Reverse(sort.Ints(keys)))

来源: http://golang.org/pkg/sort/#Reverse



然而,我收到了下面的错误:

 #command-line-arguments 
./Roman_Numerals.go: 31:sort.Ints(keys)用作值


解决方案

sort.Ints 是一种便捷的函数,用于对几个整数进行排序。一般来说,如果您想对某些内容进行排序并且sort.Reverse 只是返回该接口的一个不同实现,它重新定义了 Less 方法。



幸运的是,排序包中包含一个名为 IntSlice 的预定义类型,用于实现排序。接口:

 键:= [] int {3,2,8,1} 
sort.Sort sort.Reverse(sort.IntSlice(keys)))
fmt.Println(keys)


I am trying to reverse-sort a slice of integers in Go.

  example := []int{1,25,3,5,4}
  sort.Ints(example) // this will give me a slice sorted from 1 to the highest number

How do I sort it so that it goes from highest to lowest? so [25 5 4 3 1]

I have tried this

sort.Sort(sort.Reverse(sort.Ints(keys)))

Source: http://golang.org/pkg/sort/#Reverse

However, I am getting the error below

# command-line-arguments
./Roman_Numerals.go:31: sort.Ints(keys) used as value

解决方案

sort.Ints is a convenient function to sort a couple of ints. Generally you need to implement the sort.Interface interface if you want to sort something and sort.Reverse just returns a different implementation of that interface that redefines the Less method.

Luckily the sort package contains a predefined type called IntSlice that implements sort.Interface:

keys := []int{3, 2, 8, 1}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
fmt.Println(keys)

这篇关于如何对一个整数Go的片断进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆