简体   繁体   English

操纵包含数字的字符串列表以输出数字列表

[英]manipulation of a list of strings containing digits to output a list of of digits

I looking for help in manipulating a list of strings where I want to extract the digits such has : 我在处理要提取数字的字符串列表时寻求帮助:

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

I am trying to get to : 我想去:

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

in a elegant fashion. 以优雅的方式。

The first number should always be an integer but the second number can be a float with a decimal value 第一个数字应始终为整数,但第二个数字可以为带十进制值的浮点数

my dirty work around is this: 我周围的肮脏工作是这样的:

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]]

Use a regular expression to match integers and floats. 使用正则表达式匹配整数和浮点数。

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

Explanation for the regex ( r'\\d+\\.?\\d*' ): 正则表达式( 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM