将来自控制台的字符串输入片段转换为数字片段

I'm trying to write a Go script that takes in as many lines of comma-separated coordinates as the user wishes, split and convert the string of coordinates to float64, store each line as a slice, and then append each slice in a slice of slices for later usage.

Example inputs are:

1.1,2.2,3.3
3.14,0,5.16

Example outputs are:

[[1.1 2.2 3.3],[3.14 0 5.16]]

The equivalent in Python is

def get_input():
    print("Please enter comma separated coordinates:")
    lines = []
    while True:
        line = input()
        if line:
            line = [float(x) for x in line.replace(" ", "").split(",")]
            lines.append(line)
        else:
            break
    return lines

But what I wrote in Go seems way too long (pasted below), and I'm creating a lot of variables without the ability to change variable type as in Python. Since I literally just started writing Golang to learn it, I fear my script is long as I'm trying to convert Python thinking into Go. Therefore, I would like to ask for some advice as to how to write this script shorter and more concise in Go style? Thank you.

package main

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

func main() {
    inputs := get_input()
    fmt.Println(inputs)
}

func get_input() [][]float64 {
    fmt.Println("Please enter comma separated coordinates: ")

    var inputs [][]float64

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        if len(scanner.Text()) > 0 {
            raw_input := strings.Replace(scanner.Text(), " ", "", -1)
            input := strings.Split(raw_input, ",")
            converted_input := str2float(input)
            inputs = append(inputs, converted_input)
        } else {
            break
        }
    }

    return inputs
}

func str2float(records []string) []float64 {

    var float_slice []float64

    for _, v := range records {
        if s, err := strconv.ParseFloat(v, 64); err == nil {
            float_slice = append(float_slice, s)
        }
    }

    return float_slice
}
dongxian7194
dongxian7194 并发代码。Python不是真正的多线程(请查找“python全局解释器锁”),因此典型的纯python代码仅使用一个CPU。go中的Goroutine(又称绿色线程)在OS线程上多路复用,因此该程序实际上使用了所有CPU。通道是在goroutines之间传递对象的队列。
大约 3 年之前 回复
douli1872
douli1872 就我个人而言,由于我过于依赖Python,因此我正在用Java和Go编写一些练习。goroutine/通道在哪些应用中很常见?
大约 3 年之前 回复
dongmen1860
dongmen1860 来自Python(我也这样做),golang仅对速度和goroutines/通道感兴趣。
大约 3 年之前 回复
douzhang3822
douzhang3822 谢谢:)老实说,这是我第一次使用Python以外的方法独立解决问题。它有助于我欣赏Python的简单性。
大约 3 年之前 回复
doublestar2014
doublestar2014 是的,在for循环返回之后,检查扫描程序是否可以真正解析内容
大约 3 年之前 回复
doulaobi7988
doulaobi7988 非常感谢您的评论。我刚刚在扫描仪上查看了Golang的文档。如果err:=scan.Err();是不是该行?err!=nil...应该添加以检测任何错误?
大约 3 年之前 回复
douzaipou3327
douzaipou3327 对我来说看上去很好。Golang可能不如普通C那样冗长,但是几乎没有什么比简洁的代码更胜一筹了……顺便说一句,它应该更长一些:您应该在for循环之后检查scanner.Err()。
大约 3 年之前 回复

2个回答

Using only string functions:

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    var result [][]float64
    var txt string
    for scanner.Scan() {
        txt = scanner.Text()
        if len(txt) > 0 {
            values := strings.Split(txt, ",")
            var row []float64
            for _, v := range values {
                fl, err := strconv.ParseFloat(strings.Trim(v, " "), 64)
                if err != nil {
                    panic(fmt.Sprintf("Incorrect value for float64 '%v'", v))
                }
                row = append(row, fl)
            }
            result = append(result, row)
        }
    }
    fmt.Printf("Result: %v
", result)
}

Run:

$ printf "1.1,2.2,3.3
3.14,0,5.16
2,45,76.0, 45 , 69" | go run experiment2.go

Result: [[1.1 2.2 3.3] [3.14 0 5.16] [2 45 76 45 69]]
doubai9014
doubai9014 嗨,尤金,谢谢分享您的解决方案! 真的很像您的想法在命令行中写入所有输入数据:)
大约 3 年之前 回复

With given input, you can concatenate them to make a JSON string and then unmarshal (deserialize) that:

func main() {
    var lines []string
    for {
        var line string
        fmt.Scanln(&line)
        if line == "" {
            break
        }
        lines = append(lines, "["+line+"]")
    }
    all := "[" + strings.Join(lines, ",") + "]"
    inputs := [][]float64{}
    if err := json.Unmarshal([]byte(all), &inputs); err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(inputs)
}
douyeke2695
douyeke2695 谢谢卡夫。 我从未将JSON与Go结合使用,并且会对其进行研究!
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐