在 Go 中读取一行数字

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

5
2 1 0 3 4

在 Python 中,我可以在不指定计数 (N) 的情况下读取数字:

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

我怎样才能在 Go 中做同样的事情?或者我必须确切地知道有多少个数字?


心有法竹
浏览 221回答 2
2回答

慕无忌1623718

您可以使用 bufio 逐行遍历文件,并且该strings模块可以将字符串拆分为 slice。所以这让我们得到类似的东西:package mainimport (    "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 mainimport (    "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 stringsfunc 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 intfunc 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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go