【问题标题】:python: extract float from a python list of string( AUD 31.99)python:从 python 字符串列表中提取浮点数(31.99 澳元)
【发布时间】:2023-03-27 10:05:01
【问题描述】:

python:从字符串的 python 列表中提取浮点数(31.99 澳元)。 我使用 openpyxl 从 excel 文件中读取金额列表。我把它保存在一个列表中,但列表是这样的字符串形式:

['31.40 AUD', ' 32.99 AUD', '37.24 AUD']

我需要从字符串项列表中获取浮点数,以便稍后将其保存在新列表中以获取它们的总数。

期望的输出:

[31.40, 32.99, 37.24]

我已经尝试过这些:

newList = re.findall("\d+\.\d+", tot[0])
print(newList)

输出:

[31.40]

但是如何将它用于所有项目元素?

我是 python 新手,这只是我做的一些工作,想看看使用 python 的总数,而不是使用 excel 的查找和替换选项。 谢谢

【问题讨论】:

  • 您应该在创建列表之前进行转换。
  • 你已经接近了..但你只是通过了 tot[0]。
  • 试试[item.split()[0] for item in ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']]
  • 是否必须使用正则表达式?

标签: python regex excel list openpyxl


【解决方案1】:

你可以使用map函数:

inList = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
output = list(map(lambda elem: float(elem.split()[0]), inList))
print(output)

输出:

[31.4, 32.99, 37.24]

【讨论】:

  • @AnamulChoudhury 不客气。如果它对您有帮助,请随时接受它作为答案:)
【解决方案2】:

如果您想使用正则表达式获取值列表,请尝试

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(re.search('\d+\.\d+', fl).group(0)) for fl in tot]
print(newList)
# [31.40, 32.99, 37.24]

但在这种情况下使用split 似乎更容易解决

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(item.split()[0]) for item in tot] 
print(newList)
# [31.40, 32.99, 37.24]

如果第二个子字符串总是相同的 ("AUD") 你也可以试试

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(item.rstrip(' AUD')) for item in tot] 
print(newList)
# [31.40, 32.99, 37.24]

【讨论】:

    【解决方案3】:

    是否可以使用字符串拆分代替?我觉得会简单很多

    ls1 = ['32.46 AUD', '17.34 AUD']
    
    myFloats = []
    for aString in ls1:
        aFloat = float(aString.split()[0])
        myFloats.append(aFloat)
    

    【讨论】:

      【解决方案4】:

      您应该考虑处理错误。例如,这是一种方法:

      import re
      import math
      
      def float_from_string(str_):
          # Try to extract a floating number, if fail return nan
          r = re.search('\d+\.\d+', str_)
          return float(r.group()) if r else math.nan
      
      tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD', ' nonumberhere AUD']
      totfloat = [float_from_string(i) for i in tot]
      
      print(totfloat)
      

      返回:

      [31.4, 32.99, 37.24, nan]
      

      【讨论】:

        猜你喜欢
        • 2022-09-23
        • 1970-01-01
        • 2017-01-19
        • 2014-07-12
        • 2014-02-05
        • 2016-12-31
        • 1970-01-01
        • 2021-10-09
        • 1970-01-01
        相关资源
        最近更新 更多