【问题标题】:Python: Merge strings and convert to list of floats [closed]Python:合并字符串并转换为浮点数列表[关闭]
【发布时间】:2020-07-21 12:05:06
【问题描述】:

我有几个包含数字作为字符串的凌乱列表。一个典型的列表如下所示:

example = ['2', '0', '1', '3', ' ', '=', ' ', '[', '3', '2', '.', '9', '8', ',', ' ', '3', '2', '.', '9', '7', ',', ' ', '3', '2', '.', '5', '9', ']', '\n']

我想将其转换为单个“逗号”分隔的浮点数列表。使用上面的列表示例,理想的清理列表应该是:

cleanedExample = [32.98, 32.97, 32.59]

浮点数的长度不固定,所以有时可能会出现三位小数。

我怎样才能做到这一点?

【问题讨论】:

    标签: python string list list-comprehension


    【解决方案1】:

    首先您需要提取括号之间的位,然后将字符串连接在一起以便您可以用逗号分隔,最后映射float 以获取浮点列表。

    firstBracketIndex = example.index('[') + 1
    secondBracketIndex = example.index(']')
    numberStrings = ''.join(example[firstBracketIndex:secondBracketIndex]).split(', ')
    numbers = list(map(float, numberStrings))
    print(numbers)
    

    在此处查看实际操作 -> https://repl.it/@LukeStorry/63014174

    【讨论】:

      【解决方案2】:

      鉴于您的字符数组不只包含浮点数,我认为将数组转换为字符串并使用正则表达式提取浮点数(例如此处定义的)然后解析这些浮点数会更好成数字。

      例如

      exampleString = "2013 = [32.98, 32.97]\n"
      
      floatRegex = re.compile(r"[-+]?[0-9]*\.?[0-9]+")
      
      cleaned = [float(match) for match in floatRegex.findAll(exampleString)]
      

      这目前与 2013 年匹配,但您可以改进正则表达式以仅捕获 [] 内的值

      【讨论】:

        【解决方案3】:

        这种简单的方法可能会有所帮助:

        example = ['3', '2', '.', '9', '8', ',', '', '3', '2', '.', '9', '7', ',', ' ', '3', '2', '.', '5', '9']
        float_string = ''
        cleanedExample = []
        for letter in example:
            if letter == ',':
                cleanedExample.append(float(float_string))
                float_string = ''
            else:    
                float_string += letter 
        
        print(cleanedExample) 
        output: [32.98, 32.97] 
        
          
        

        【讨论】:

          【解决方案4】:

          试试下面这个:

          example = ['2', '0', '1', '3', ' ', '=', ' ', '[', '3', '2', '.', '9', '8', ',', ' ', '3', '2', '.', '9', '7', ',', ' ', '3', '2', '.', '5', '9', ']', '\n']
          result = list(map(float, "".join(example).split("= ")[-1][1:-2].split(",")))
          # [32.98, 32.97, 32.59]
          

          【讨论】:

          • 我们不知道这种格式有多标准。
          • 这应该由OP声明。它可以使用格式xxx = [....whatever]\n。无论如何,它可以使用OP发布的格式。更多细节应该由OP发布。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-20
          • 1970-01-01
          相关资源
          最近更新 更多