2016-10-04 40 views
1

我在操縱,我想提取這種數字的字符串列表尋求幫助列表字符串列表的有:操縱包含數字輸出的數字

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

以優雅的方式。

第一個數字應始終是一個整數,但第二個數字可與十進制值的浮動

我骯髒的解決辦法是這樣的:

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

將字符串總是'%'結束? –

+0

@ Farhan.K總是 –

+0

既然你正在轉換爲'float',那麼在字符串中出現非整數的機會呢?每個字符串總是會有兩個數字嗎? –

回答

7

使用regular expression匹配整數和浮點數。

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) 
+0

謝謝,看着重新模塊。我的不好,問題不清楚,有十進制數的可能性。 –

+0

你能快速解釋一下r'\ d + \?嗎?\ d *'我真的很不滿意。謝謝! –

+0

@StevenG:更新瞭解釋正則表達式的答案。 –