将从控制台输入的字符串切片转换为数字切片。

huangapple go评论176阅读模式
英文:

Convert slice of string input from console to slice of numbers

问题

我正在尝试编写一个Go脚本,它接受用户希望输入的任意行以逗号分隔的坐标,将坐标字符串拆分并转换为float64,将每行存储为切片,然后将每个切片附加到切片的切片中以供以后使用。

示例输入为:

  1. 1.1,2.2,3.3
  2. 3.14,0,5.16

示例输出为:

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

在Python中的等效代码如下:

  1. def get_input():
  2. print("Please enter comma separated coordinates:")
  3. lines = []
  4. while True:
  5. line = input()
  6. if line:
  7. line = [float(x) for x in line.replace(" ", "").split(",")]
  8. lines.append(line)
  9. else:
  10. break
  11. return lines

但是我在Go中编写的代码似乎太长了(如下所示),而且我创建了很多变量,而且不能像Python那样更改变量类型。由于我刚刚开始学习Go语言,我担心我的脚本太长了,因为我试图将Python的思维转换为Go。因此,我想请教一些建议,如何以更短、更简洁的Go风格编写这个脚本?谢谢。

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "bufio"
  6. "strings"
  7. "strconv"
  8. )
  9. func main() {
  10. inputs := get_input()
  11. fmt.Println(inputs)
  12. }
  13. func get_input() [][]float64 {
  14. fmt.Println("Please enter comma separated coordinates: ")
  15. var inputs [][]float64
  16. scanner := bufio.NewScanner(os.Stdin)
  17. for scanner.Scan() {
  18. if len(scanner.Text()) > 0 {
  19. raw_input := strings.Replace(scanner.Text(), " ", "", -1)
  20. input := strings.Split(raw_input, ",")
  21. converted_input := str2float(input)
  22. inputs = append(inputs, converted_input)
  23. } else {
  24. break
  25. }
  26. }
  27. return inputs
  28. }
  29. func str2float(records []string) []float64 {
  30. var float_slice []float64
  31. for _, v := range records {
  32. if s, err := strconv.ParseFloat(v, 64); err == nil {
  33. float_slice = append(float_slice, s)
  34. }
  35. }
  36. return float_slice
  37. }
英文:

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.1,2.2,3.3
  2. 3.14,0,5.16

Example outputs are:

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

The equivalent in Python is

  1. def get_input():
  2. print("Please enter comma separated coordinates:")
  3. lines = []
  4. while True:
  5. line = input()
  6. if line:
  7. line = [float(x) for x in line.replace(" ", "").split(",")]
  8. lines.append(line)
  9. else:
  10. break
  11. 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.

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "bufio"
  6. "strings"
  7. "strconv"
  8. )
  9. func main() {
  10. inputs := get_input()
  11. fmt.Println(inputs)
  12. }
  13. func get_input() [][]float64 {
  14. fmt.Println("Please enter comma separated coordinates: ")
  15. var inputs [][]float64
  16. scanner := bufio.NewScanner(os.Stdin)
  17. for scanner.Scan() {
  18. if len(scanner.Text()) > 0 {
  19. raw_input := strings.Replace(scanner.Text(), " ", "", -1)
  20. input := strings.Split(raw_input, ",")
  21. converted_input := str2float(input)
  22. inputs = append(inputs, converted_input)
  23. } else {
  24. break
  25. }
  26. }
  27. return inputs
  28. }
  29. func str2float(records []string) []float64 {
  30. var float_slice []float64
  31. for _, v := range records {
  32. if s, err := strconv.ParseFloat(v, 64); err == nil {
  33. float_slice = append(float_slice, s)
  34. }
  35. }
  36. return float_slice
  37. }

答案1

得分: 2

使用字符串函数:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. func main() {
  10. scanner := bufio.NewScanner(os.Stdin)
  11. var result [][]float64
  12. var txt string
  13. for scanner.Scan() {
  14. txt = scanner.Text()
  15. if len(txt) > 0 {
  16. values := strings.Split(txt, ",")
  17. var row []float64
  18. for _, v := range values {
  19. fl, err := strconv.ParseFloat(strings.Trim(v, " "), 64)
  20. if err != nil {
  21. panic(fmt.Sprintf("Incorrect value for float64 '%v'", v))
  22. }
  23. row = append(row, fl)
  24. }
  25. result = append(result, row)
  26. }
  27. }
  28. fmt.Printf("Result: %v\n", result)
  29. }

运行:

  1. $ printf "1.1,2.2,3.3
  2. 3.14,0,5.16
  3. 2,45,76.0, 45 , 69" | go run experiment2.go
  4. Result: [[1.1 2.2 3.3] [3.14 0 5.16] [2 45 76 45 69]]

以上是给定的代码,它使用字符串函数将输入的文本解析为浮点数矩阵,并将结果打印出来。

英文:

Using only string functions:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. func main() {
  10. scanner := bufio.NewScanner(os.Stdin)
  11. var result [][]float64
  12. var txt string
  13. for scanner.Scan() {
  14. txt = scanner.Text()
  15. if len(txt) > 0 {
  16. values := strings.Split(txt, ",")
  17. var row []float64
  18. for _, v := range values {
  19. fl, err := strconv.ParseFloat(strings.Trim(v, " "), 64)
  20. if err != nil {
  21. panic(fmt.Sprintf("Incorrect value for float64 '%v'", v))
  22. }
  23. row = append(row, fl)
  24. }
  25. result = append(result, row)
  26. }
  27. }
  28. fmt.Printf("Result: %v\n", result)
  29. }

Run:

  1. $ printf "1.1,2.2,3.3
  2. 3.14,0,5.16
  3. 2,45,76.0, 45 , 69" | go run experiment2.go
  4. Result: [[1.1 2.2 3.3] [3.14 0 5.16] [2 45 76 45 69]]

答案2

得分: 1

使用给定的输入,您可以将它们连接起来以生成一个JSON字符串,然后进行反序列化:

  1. func main() {
  2. var lines []string
  3. for {
  4. var line string
  5. fmt.Scanln(&line)
  6. if line == "" {
  7. break
  8. }
  9. lines = append(lines, "["+line+"]")
  10. }
  11. all := "[" + strings.Join(lines, ",") + "]"
  12. inputs := [][]float64{}
  13. if err := json.Unmarshal([]byte(all), &inputs); err != nil {
  14. fmt.Println(err)
  15. return
  16. }
  17. fmt.Println(inputs)
  18. }
英文:

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

  1. func main() {
  2. var lines []string
  3. for {
  4. var line string
  5. fmt.Scanln(&line)
  6. if line == "" {
  7. break
  8. }
  9. lines = append(lines, "["+line+"]")
  10. }
  11. all := "[" + strings.Join(lines, ",") + "]"
  12. inputs := [][]float64{}
  13. if err := json.Unmarshal([]byte(all), &inputs); err != nil {
  14. fmt.Println(err)
  15. return
  16. }
  17. fmt.Println(inputs)
  18. }

huangapple
  • 本文由 发表于 2017年9月11日 02:10:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/46143974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定