为了账号安全,请及时绑定邮箱和手机立即绑定

如何并排打印键和值?

如何并排打印键和值?

Go
Helenr 2023-02-06 14:44:41
在此代码中,我打印了角色,并且对于每个角色,我都想写下附加到它的密钥。但我不知道该怎么做。如果我i < 3在 for 循环中写入,那么这三个键将被打印六次,因为该roles变量包含六个字符串值。package mainimport "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 nameHere is the name: first emailHere is the name: first roleHere is the name: second nameHere is the name: second emailHere is the name: second role要求的结果Here is the name: first nameHere is the email address: first emailHere is the job role: first roleHere is the name: second nameHere is the email address: second emailHere is the job role: second role
查看完整描述

1 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

使用整数 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 roles

for i := range roles {

    // j is index into keys

    j := i % len(keys)


    // Print blank line between groups.

    if j == 0 && i > 0 {

        fmt.Println()

    }


    fmt.Printf("Here is the %s: %s\n", keys[j], roles[i])

}

在 playground 上运行示例



查看完整回答
反对 回复 2023-02-06
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信