如何输出迭代切片的前 N ​​个元素?

我需要取申请人的名字、名字和 GPA,然后只输出前 N 个申请人。比如我有5个申请者,但是只有N=3可以通过。为了完成这项任务,我决定使用一片结构。


该结构如下所示:


type Applicant struct {

    firstName  string

    secondName string

    GPA        float64

}

我创建了一个切片并对其进行了初始化:


applicants := []Applicant{}

...

fmt.Scan(&firstName, &lastName, &GPA)

applicants = append(applicants, Applicant{firstName, lastName, GPA})

现在我的任务是只输出GPA 最高的前 3名申请人的姓名。我已经从最好的 GPA 到最差的 GPA 进行了排序。


我尝试像这样输出申请者切片,但出现错误:


for _, applicant := range applicants {

    fmt.Println(applicant.secondName + " " + applicant.secondName)

}

你能帮我输出切片名称吗?


慕尼黑的夜晚无繁华
浏览 122回答 3
3回答

明月笑刀无情

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

蓝山帝景

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

aluckdog

如果您的任务真的只是打印出名字,那么这是一种可能的方法&nbsp; for i := 0; i < 3 && i < len(applicants); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s %s\n", applicants[i].firstName, applicants[i].secondName)&nbsp; &nbsp; }请注意,必须首先对列表进行排序,就像其他帖子中显示的那样。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go