dongpixi2648 2017-09-10 18:10
浏览 65
已采纳

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

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
}
  • 写回答

2条回答 默认 最新

  • doudao1282 2017-09-11 13:33
    关注

    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]]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?