为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中读取一行数字

在 Go 中读取一行数字

Go
心有法竹 2023-02-06 10:18:37
我有以下输入,其中第一行是 N - 数字计数,第二行是 N 个数字,以空格分隔:5 2 1 0 3 4在 Python 中,我可以在不指定计数 (N) 的情况下读取数字:_ = input() numbers = list(map(int, input().split()))我怎样才能在 Go 中做同样的事情?或者我必须确切地知道有多少个数字?
查看完整描述

2 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

您可以使用 bufio 逐行遍历文件,并且该strings模块可以将字符串拆分为 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]


查看完整回答
反对 回复 2023-02-06
?
守候你守候我

TA贡献1802条经验 获得超10个赞

由于您知道定界符并且只有 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]


查看完整回答
反对 回复 2023-02-06
  • 2 回答
  • 0 关注
  • 220 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号