go - Golang - Convert slice of string input from console to slice of numbers -


i'm trying write go script takes in many lines of comma-separated coordinates user wishes, split , convert string of coordinates float64, store each line slice, , append each slice in slice of slices 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) x in line.replace(" ", "").split(",")]             lines.append(line)         else:             break     return lines 

but wrote in go seems way long (pasted below), , i'm creating lot of variables without ability change variable type in python. since literally started writing golang learn it, fear script long i'm trying convert python thinking go. therefore, ask advice how write script shorter , 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)     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      _, v := range records {         if s, err := strconv.parsefloat(v, 64); err == nil {             float_slice = append(float_slice, s)         }     }      return float_slice } 

with given input, can concatenate them make json string , unmarshal (deserialize) that:

func main() {     var lines []string     {         var line string         fmt.scanln(&line)         if line == "" {             break         }         lines = append(lines, "["+line+"]")     }     := "[" + strings.join(lines, ",") + "]"     inputs := [][]float64{}     if err := json.unmarshal([]byte(all), &inputs); err != nil {         fmt.println(err)         return     }      fmt.println(inputs) } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -