英文:
How to print the keys and values side by side?
问题
在这段代码中,我打印了角色,并且对于每个角色,我想要写入与之相关联的键。但是我不知道如何做到这一点。如果我在for循环中写入i < 3
,那么这三个键会被打印六次,因为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 i := 0; i < len(roles); i += 3 {
fmt.Println("Here is the "+keys[i/3]+":", roles[i])
fmt.Println("Here is the "+keys[i/3+1]+":", roles[i+1])
fmt.Println("Here is the "+keys[i/3+2]+":", roles[i+2])
}
}
给定结果
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
英文:
In this code, I print the roles, and with every role, I want to write the key attached to it. But I don't know how to do it. If I write i < 3
in for loop then the three keys are printed six times because the roles
variable contains six string values.
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)
}
}
}
Given Result
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
Required Result
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
答案1
得分: 1
使用整数取模运算符将角色索引转换为键索引:
roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"}
keys := []string{"name", "email address", "job role"}
// i 是 roles 的索引
for i := range roles {
// j 是 keys 的索引
j := i % len(keys)
// 在分组之间打印空行。
if j == 0 && i > 0 {
fmt.Println()
}
fmt.Printf("这是 %s:%s\n", keys[j], roles[i])
}
英文:
Use the integer mod operator to convert a roles index to a keys index:
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])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论