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

WBOY
Release: 2024-02-06 10:06:07
forward
729 people have browsed it

如何在 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
Copy after login

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

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

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

        }
    }
}
Copy after login


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])
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!