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

wor*_*rum 1 go slice

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

该结构如下所示:

type Applicant struct {
    firstName  string
    secondName string
    GPA        float64
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个切片并初始化它:

applicants := []Applicant{}
...
fmt.Scan(&firstName, &lastName, &GPA)
applicants = append(applicants, Applicant{firstName, lastName, GPA})
Run Code Online (Sandbox Code Playgroud)

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

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

for _, applicant := range applicants {
    fmt.Println(applicant.secondName + " " + applicant.secondName)
}
Run Code Online (Sandbox Code Playgroud)

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

Aus*_*ter 7

要获得 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]
}
Run Code Online (Sandbox Code Playgroud)

要获取名称,您可以创建一个新切片

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
}
Run Code Online (Sandbox Code Playgroud)

  • 请记住,如果切片小于 3 个元素,则可能会出现索引越界错误。 (3认同)