【问题标题】:I want to extract numbers from a list with strings我想从带有字符串的列表中提取数字
【发布时间】:2020-01-26 13:28:33
【问题描述】:

我有一个包含字符串的列表:list = ['string', 'string', 'string', ...]
这些字符串就像:'NumberDescription 33.3'
我只想提取没有'NumberDescription' part.的数字

我已经尝试过使用正则表达式和使用 re.match 的过滤器功能。 但这会导致一个空列表。

dat_re = re.compile(r'\d+.\d')  
dat_list = list(filter(dat_re.match, list))

正如我所说,我只想要列表中的数字,在最后一步中,我想将列表中的元素转换为浮点数。

【问题讨论】:

  • 1) 使用re.search, 2) 转义点
  • 所以dat_re = re.compile(r'\d+\.\d')dat_list = list(filter(dat_re.search, list))?不工作。搜索返回初始列表。
  • 但是您只过滤列表,不提取值。 dat_list = [dat_re.search(x).group() for x in l if dat_re.search(x)]

标签: python regex python-3.x list


【解决方案1】:

这里有几点:

  1. 使用re.search,因为re.match only searches for the match at the string start
  2. 转义点,因为它是special regex metacharacter
  3. 您仅使用filter(...) 过滤列表,不提取值。
  4. 如果您打算查找digit+.digit+ 第一次出现,您可以使用像\d+\.\d+ 这样的正则表达式
  5. 如果您的商品全部采用string number 格式,请使用s.split()[-1] 获取编号,无需正则表达式

使用

dat_list = [float(dat_re.search(x).group()) for x in l if dat_re.search(x)]

或者,如果格式是固定的

dat_list = [float(x.split()[-1]) for x in l]

Python demo

import re
l = ['string 23.3', 'NumberDescription 33.35']
dat_re = re.compile(r'\d+\.\d+')
dat_list = [float(dat_re.search(x).group()) for x in l if dat_re.search(x)]
print(dat_list)
# => [23.3, 33.35]
print([float(x.split()[-1]) for x in l])
# => [23.3, 33.35]

【讨论】:

    【解决方案2】:
    list_strings=['1','2','3']
    for i in list_strings:
        num_list.append(int(i))
    or
    
    list_num = [int(x) for x in list_strings]
    

    检查此示例代码一次。

    【讨论】:

      【解决方案3】:

      直接从列表中提取浮点值:

      import re
      l = ['string 23.3', 'string 33.35', 'string 44.55']
      dat_list = list(float(match.group(1)) for match in map(re.compile('(\d+\.\d+)').search, l))
      print(dat_list)
      

      输出:

       [23.3, 33.35, 44.55]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多