Skip to main content
 首页 » 编程设计

python之操作包含数字的字符串列表以输出数字列表

2025年05月04日19grandyang

我正在寻求帮助来处理我想提取数字的字符串列表,例如:

 x = ['aa bb qq 2 months  60%', 'aa bb qq 3 months  70%', 'aa bb qq 1 month  80%'] 

我正在尝试:

[[2.0,60.0],[3.0,70.0],[1.0,80.0]] 

以优雅的方式。

第一个数字应该始终是整数,但第二个数字可以是带小数值的 float

我的肮脏工作是这样的:

x_split = [y.replace("%", "").split() for y in x] 
x_float = [[float(s) for s in x if s.isdigit()] for x in x_split] 
 
Out[100]: [[2.0, 60.0], [3.0, 70.0], [1.0, 80.0]] 

请您参考如下方法:

使用 regular expression匹配整数和 float 。

import re 
[[float(n) for n in re.findall(r'\d+\.?\d*', s)] for s in x] 

正则表达式的解释(r'\d+\.?\d*'):

r    #  a raw string so that back slashes are not converted   
\d   #  digit 0 to 9 
+    #  one or more of the previous pattern (\d) 
\.   #  a decimal point 
?    #  zero or one of the previous pattern (\.) 
\d   #  digit 0 to 9 
*    #  zero or more of the previous pattern (\d)