如何并排打印键和值?

在此代码中,我打印了角色,并且对于每个角色,我都想写下附加到它的密钥。但我不知道该怎么做。如果我i < 3在 for 循环中写入,那么这三个键将被打印六次,因为该roles变量包含六个字符串值。


package main


import "fmt"


func main() {

    roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"}

    keys := [3]string{"name", "email address", "job role"}

    for _, data := range roles {

        for i := 0; i < 1; i++ {

            fmt.Println("Here is the "+keys[i]+":", data)

        }

    }

}

给出的结果


Here is the name: first name

Here is the name: first email

Here is the name: first role

Here is the name: second name

Here is the name: second email

Here is the name: second role

要求的结果


Here is the name: first name

Here is the email address: first email

Here is the job role: first role


Here is the name: second name

Here is the email address: second email

Here is the job role: second role


Helenr
浏览 118回答 1
1回答

慕雪6442864

使用整数 mod 运算符将角色索引转换为键索引:roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"}keys := []string{"name", "email address", "job role"}// i is index into rolesfor i := range roles {&nbsp; &nbsp; // j is index into keys&nbsp; &nbsp; j := i % len(keys)&nbsp; &nbsp; // Print blank line between groups.&nbsp; &nbsp; if j == 0 && i > 0 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println()&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("Here is the %s: %s\n", keys[j], roles[i])}在 playground 上运行示例。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go