Home  >  Article  >  Backend Development  >  How to normalize (1:N) a csv file to a map in Go?

How to normalize (1:N) a csv file to a map in Go?

WBOY
WBOYforward
2024-02-06 10:06:07730browse

如何在 Go 中将 csv 文件规范化 (1:N) 为地图?

Question content

I am trying to normalize the structure of a csv file as follows:

name, note
'joe', 5
'joe', 3
'ashley', 1
'ashley', 7
'ashley', 4

to a map, after reading the file, will be reduced to:

map [string][]string{
    "joe" = {5, 3},
    "ashley" = {1, 7, 4},
}

What's the best way?

I am new to go, the code I created is 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)
            }

        }
    }
}

Correct answer


It should be very simple:

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])
}

The above is the detailed content of How to normalize (1:N) a csv file to a map in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete