ITPub博客

首页 > 应用开发 > IT综合 > 将字符串数组转换为浮点数数组

将字符串数组转换为浮点数数组

IT综合 作者:itchaindev 时间:2022-04-06 12:02:37 0 删除 编辑

问题

我正在编写一个围绕从文件中获取数值数据集的应用程序。 但是,由于数据是以字符串形式获取的,所以我必须将其转换为浮点数,这就是有趣的开始。 我的代码的相关部分如图所示(第 65-73 行):

    ft = []
    puts "File Name: #{ARGV[0]}"
    File.open(ARGV[0], "r") do |file|
        file.each_line do |line|
            ft << line.scan(/\d+/)        end
    endft.collect! {|i| i.to_f}

这在 irb 中工作得很好,也就是说,最后一行将数组更改为浮点数。

irb(main):001:0> ft = ["10", "23", "45"]=> ["10", "23", "45"]irb(main):002:0> ft.collect! {|i| i.to_f}=> [10.0, 23.0, 45.0]

但是,当我运行我的应用程序时,出现此错误:

ruby-statistics.rb:73:in `block in <main>': undefined method `to_f' for #<Array:
0x50832c> (NoMethodError)
        from ruby-statistics.rb:73:in `collect!'
        from ruby-statistics.rb:73:in `<main>'

对此的任何帮助将不胜感激。



解决方案

阅读文件后,您应该查看“ft”的格式。

每一行都存储在另一个数组中,所以实际上“ft”看起来像这样:

[["1","2"],["3","4"]]

所以你必须做这样的事情:

ft = []puts "File Name: #{ARGV[0]}"File.open(ARGV[0], "r") do |file|
    file.each_line do |line|
            ft << line.scan(/\d+/)    endendtmp = []ft.each do |line|
    line.each do |number|
        tmp << number.to_f
    endendputs tmp

这只是一个猜测,因为我不知道您的文件格式是什么样的。

编辑:

这里作为一个单行:

ft.flatten!.collect! { |i| i.to_f }

 

line.scan返回一个数组,因此您将一个数组插入到一个数组中。 flatten最简单的做法是在将字符串转换为浮点数之前调用数组。

ft = []puts "File Name: #{ARGV[0]}"File.open(ARGV[0], "r") do |file|
    file.each_line do |line|
            ft << line.scan(/\d+/)    endendft = ft.flatten.collect { |i| i.to_f }




 原文连接:
将字符串数组转换为浮点数数组


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70016198/viewspace-2885754/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2022-04-02

  • 博文量
    12
  • 访问量
    3420