3 回答

TA贡献1828条经验 获得超4个赞
要获得 GPA 最高的前 3 个,您首先对切片进行排序(您已经做过),然后创建一个子切片:
func GetTopThree(applicants []Applicant) []Applicant {
sort.Slice(applicants, func(i, j int) bool {
return applicants[i].GPA > applicants[j].GPA
})
return applicants[:3]
}
要获取名称,您可以创建一个新切片
func GetTopThreeNames(applicants []Applicant) []string {
var topThree []string
for i := 0; i < int(math.Min(3, float64(len(applicants)))); i++ {
topThree = append(topThree, applicants[i].firstName)
}
return topThree
}

TA贡献1843条经验 获得超7个赞
如果您想分别映射名字和姓氏,这可能是一种方法:
func TopThreeNames(applicants []Applicant) [][2]string {
top := applicants[:int(math.Min(3, float64(len(applicants))))]
var names [][2]string
for _, a := range top {
names = append(names, [2]string{a.firstName, a.secondName})
}
return names
}
该函数将每个元素映射Applicant到长度为 2 的数组,其中第一个元素等于其名字,第二个元素等于其名字。
例如(不安全,因为切片的长度可能为空):
names := TopThreeNames(applicants)
first := names[0]
fmt.Printf("First name: %s and last name: %s\n", first[0], first[1])

TA贡献1847条经验 获得超7个赞
如果您的任务真的只是打印出名字,那么这是一种可能的方法
for i := 0; i < 3 && i < len(applicants); i++ {
fmt.Printf("%s %s\n", applicants[i].firstName, applicants[i].secondName)
}
请注意,必须首先对列表进行排序,就像其他帖子中显示的那样。
- 3 回答
- 0 关注
- 121 浏览
添加回答
举报