英文:
how to normalize (1:N) a csv file to a map in Go?
问题
我正在尝试从一个CSV文件中规范化一个结构,它的格式如下:
name, note
'Joe', 5
'Joe', 3
'Ashley', 1
'Ashley', 7
'Ashley', 4
将其转换为一个映射,读取该文件后,将被简化为:
map [string][]string{
"joe" = {5, 3},
"ashley" = {1, 7, 4},
}
最好的方法是什么?
我是Go的新手,我创建的代码大致如下:
func main() {
fileName := "new"
xlsx, err := excelize.OpenFile(fileName + ".xlsx")
if err != nil {
fmt.Println(err)
return
}
rows, err := xlsx.Rows("Sheet1")
if err != nil {
fmt.Print(err)
}
for rows.Next() {
column, err := rows.Columns()
if err != nil {
println(err)
}
for i := 0; i < 1; i++ {
if i == i {
m := map[string][]string{
column[i]: []string{column[1]},
}
fmt.Printf("%v\n", m)
}
}
}
}
英文:
I'm trying to normalize a structure from a CSV file, which is like this:
name, note
'Joe', 5
'Joe', 3
'Ashley', 1
'Ashley', 7
'Ashley', 4
to a map, that after read that file, will be reduced to:
map [string][]string{
"joe" = {5, 3},
"ashley" = {1, 7, 4},
}
what's the best approach to do that?
Im new in Go, and the code I created is something like this:
func main() {
fileName := "new"
xlsx, err := excelize.OpenFile(fileName + ".xlsx")
if err != nil {
fmt.Println(err)
return
}
rows, err := xlsx.Rows("Sheet1")
if err != nil {
fmt.Print(err)
}
for rows.Next() {
column, err := rows.Columns()
if err != nil {
println(err)
}
for i := 0; i < 1; i++ {
if i == i {
m := map[string][]string{
column[i]: []string{column[1]},
}
fmt.Printf("%v\n", m)
}
}
}
}
答案1
得分: 1
应该相当简单:
m := map[string][]string{}
for rows.Next() {
column, err := rows.Columns()
if err != nil {
panic(err)
}
if len(column) < 2 {
panic("行太短")
}
m[column[0]] = append(m[column[0]], column[1])
}
英文:
It should be pretty straightforward:
m := map[string][]string{}
for rows.Next() {
column, err := rows.Columns()
if err != nil {
panic(err)
}
if len(column) < 2 {
panic("row too short")
}
m[column[0]] = append(m[column[0]], column[1])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论