我有以下输入,其中第一行是N-数字计数,第二行是N个数字,用空格分隔:
5
2 1 0 3 4
在Python中,我可以在不指定计数(N)的情况下读取数字:
_ = input()
numbers = list(map(int, input().split()))
我怎样才能在围棋中做同样的事情?或者我必须知道确切的数字是多少?
我有以下输入,其中第一行是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]