登录
首页 >  Golang >  Go问答

在 Go 中读取一行数字数据

来源:stackoverflow

时间:2024-02-09 14:45:23 359浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《在 Go 中读取一行数字数据》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我有以下输入,其中第一行是 n - 数字计数,第二行是 n 个数字,以空格分隔:

5
2 1 0 3 4

在 python 中,我可以读取数字而不指定其计数 (n):

_ = input()
numbers = list(map(int, input().split()))

我如何在 go 中做同样的事情?或者我必须确切地知道有多少个数字?


正确答案


您可以逐行迭代文件 using bufiostrings 模块可以迭代 split a string into a slice。因此,我们可以得到如下结果:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    readfile, err := os.open("data.txt")
    defer readfile.close()

    if err != nil {
        fmt.println(err)
    }
    filescanner := bufio.newscanner(readfile)

    filescanner.split(bufio.scanlines)

    for filescanner.scan() {

        // get next line from the file
        line := filescanner.text()

        // split it into a list of space-delimited tokens
        chars := strings.split(line, " ")

        // create an slice of ints the same length as
        // the chars slice
        ints := make([]int, len(chars))

        for i, s := range chars {
            // convert string to int
            val, err := strconv.atoi(s)
            if err != nil {
                panic(err)
            }

            // update the corresponding position in the
            // ints slice
            ints[i] = val
        }

        fmt.printf("%v\n", ints)
    }
}

给定您的示例数据将输出:

[5]
[2 1 0 3 4]

由于您知道分隔符并且只有 2 行,因此这也是一个更紧凑的解决方案:

package main

import (
    "fmt"
    "os"
    "regexp"
    "strconv"
    "strings"
)

func main() {

    parts, err := readraw("data.txt")
    if err != nil {
        panic(err)
    }

    n, nums, err := tonumbers(parts)
    if err != nil {
        panic(err)
    }

    fmt.printf("%d: %v\n", n, nums)
}

// readraw reads the file in input and returns the numbers inside as a slice of strings
func readraw(fn string) ([]string, error) {
    b, err := os.readfile(fn)
    if err != nil {
        return nil, err
    }
    return regexp.mustcompile(`\s`).split(strings.trimspace(string(b)), -1), nil
}

// tonumbers plays with the input string to return the data as a slice of int
func tonumbers(parts []string) (int, []int, error) {
    n, err := strconv.atoi(parts[0])
    if err != nil {
        return 0, nil, err
    }
    nums := make([]int, 0)
    for _, p := range parts[1:] {
        num, err := strconv.atoi(p)
        if err != nil {
            return n, nums, err
        }
        nums = append(nums, num)
    }

    return n, nums, nil
}

输出为:

5: [2 1 0 3 4]

到这里,我们也就讲完了《在 Go 中读取一行数字数据》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>