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

5
2 1 0 3 4

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

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

我怎样才能在围棋中做同样的事情?或者我必须知道确切的数字是多少?

推荐答案

您可以逐行遍历文件using bufio,而strings模块可以是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]

Go相关问答推荐

切换选项卡时,Goland IDE中的光标自动转移

你能把用户界面文件中的GTK4应用程序窗口添加到GTK4应用程序中吗?

如何将GoFr筛选器用于查询参数?

使用Go使用Gorm使用外键对数据进行排序

从使用Golang otelmux检测的Otel跟踪中获取trace_id

go grpc:无法导入github.com/golang/protobuf/proto(没有所需的模块提供包github.com/gorang/protobuf-proto)

如何修复 Go 中协议缓冲区定义中重新定义的字段?

优化方式中所有可能组合的字符串相似度

带有前导零的整数参数被 flag.IntVar 解析为八进制

使用 LINQ 对内部数组进行排序

Golang crypto/rand 线程安全吗?

如何将整数哈希细分为范围

如何在切片增长时自动将切片的新元素添加到函数参数

如何使用 fyne Go 使用 canvas.NewText() 使文本可滚动

Go 泛型:自引用接口约束

使用 package`regexp` 查找 Golang 中的所有 mactch 子字符串,但得到意外结果

没有堆栈跟踪的 go 程序崩溃是什么意思?

go 堆栈跟踪:在某些函数调用参数或返回值之后的问题(?)标记是什么意思?

gqlgen go,通过添加一个解析器来减少数据库调用

获取单调时间,同 CLOCK_MONOTONIC