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

huangapple go评论76阅读模式
英文:

How to output iterate over first N elements of slice?

问题

我需要获取申请人的名字、姓氏和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})

现在我的任务是只输出前3个GPA最高的申请人的名字。我已经将切片按照GPA从高到低进行了排序。

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

for _, applicant := range applicants {
	fmt.Println(applicant.secondName + " " + applicant.secondName)
}

你能帮我解决切片名字输出的问题吗?

英文:

I need to take applicant's first name, second name and GPA, then output only the first N applicants. For example, I have 5 applicants, but only N=3 can pass through.
To do this task, I decided to use a slice of struct.

The struct looks like this:

type Applicant struct {
	firstName  string
	secondName string
	GPA        float64
}

I created a slice and initialized it:

applicants := []Applicant{}
...
fmt.Scan(&firstName, &lastName, &GPA)
applicants = append(applicants, Applicant{firstName, lastName, GPA})

Now my task is to output only names of first 3 applicants with highest GPA. I already sorted the slice from the best GPA to the worst.

I tried to do output applicants slice like this, but got error:

for _, applicant := range applicants {
	fmt.Println(applicant.secondName + " " + applicant.secondName)
}

Can you help me with slice name output?

答案1

得分: 7

获取前三个GPA最高的申请人,你首先需要对切片进行排序(你已经做过了),然后创建一个子切片:

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
}
英文:

To get the first 3 with highest GPA you first sort the slice (what you alread did) and then just create a subslice:

func GetTopThree(applicants []Applicant) []Applicant {
    sort.Slice(applicants, func(i, j int) bool {
        return applicants[i].GPA &gt; applicants[j].GPA
    })
    return applicants[:3]
}

To just get the names you can create a new slice

func GetTopThreeNames(applicants []Applicant) []string {
	var topThree []string
	for i := 0; i &lt; int(math.Min(3, float64(len(applicants)))); i++ {
		topThree = append(topThree, applicants[i].firstName)
	}
	return topThree
}

答案2

得分: 1

如果你想要分别映射名字和姓氏,可以使用以下方法:

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("名字:%s,姓氏:%s\n", first[0], first[1])
英文:

If you want to map the first names and last names separately, this could be an approach:

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
}

The function maps each Applicant element to an array of length two, whereby the first element is equal to its first name and the second element to its second name.

For instance (unsafe since the length of the slice could be empty):

names := TopThreeNames(applicants)
	
first := names[0]
fmt.Printf(&quot;First name: %s and last name: %s\n&quot;, first[0], first[1])

答案3

得分: 0

如果你的任务只是打印出姓名,那么这是一种可能的方法:

for i := 0; i < 3 && i < len(applicants); i++ {
    fmt.Printf("%s %s\n", applicants[i].firstName, applicants[i].secondName)
}

请注意,列表必须首先按照其他帖子中显示的方式进行排序。

英文:

If your task really is just to print out the names then this is one possible way

  for i := 0; i &lt; 3 &amp;&amp; i &lt; len(applicants); i++ {
		fmt.Printf(&quot;%s %s\n&quot;, applicants[i].firstName, applicants[i].secondName)
	}

Note that the list must be sorted first like is is shown in other posts.

huangapple
  • 本文由 发表于 2022年7月17日 02:44:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73006830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定