2014-04-10 52 views
1

我有一個list使用正則表達式來刪除內容在括號中的python

['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL'] 

也爲作爲字符串'14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\n'

使用正則表達式,我怎麼回:

['14147618', '6137776, '5943229', 2066613'] 

回答

5

你根本不需要RegEx,你可以簡單地過濾掉只有數字的數據,這個列表理解

print [item for item in data if item.isdigit()] 
# ['14147618', '6137776', '5943229', '2066613'] 

或者你也可以使用filter內置功能,這樣

print filter(str.isdigit, data) 
# ['14147618', '6137776', '5943229', '2066613'] 

編輯:如果您有整個數據作爲一個字符串,您可以根據空格字符分割數據,然後使用同樣的邏輯

data = '14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\n' 
print [item for item in data.split() if item.isdigit()] 
# ['14147618', '6137776', '5943229', '2066613'] 
print filter(str.isdigit, data.split()) 
# ['14147618', '6137776', '5943229', '2066613'] 
+0

ü可以告訴我,如果A =''14147618(100%)6137776 (43%)5943229(42%)2066613(14%)TOTAL \ n'' 如何獲得'['14147618','6137776,'5943229',2066613']'? – VeilEclipse

+0

@VeilEclipse你可以使用'a.split()' – thefourtheye

+0

@VeilEclipse相同的程序請檢查更新的答案。 – thefourtheye

2

正如@thefourtheye說,這是沒有必要使用正則表達式可言,但如果你真想做無線個正則表達式,你可以使用:

import re 

a = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL'] 
result = [] 

for e in a: 
    m = re.match(r'\d+', e) 
    if m is not None: 
     result.append(e) 

print result 
# ['14147618', '6137776', '5943229', '2066613'] 

注:這也可以寫成列表理解:

print [e for e in a if re.match(r'\d+', e)] 
2

這裏有一種方法:

>>> l = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL'] 
>>> [el for el in l if re.match(r'\d+$', el)] 
['14147618', '6137776', '5943229', '2066613'] 
2

使用重模塊:

>>> import re 
>>> [item for item in s if re.match(r'\d+',item)] 
['14147618', '6137776', '5943229', '2066613'] 
2

根本不需要使用re模塊,您可以使用filter而不是list

試試這個,

>>> a=['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL'] 
>>> filter(str.isdigit, a) 
['14147618', '6137776', '5943229', '2066613'] 
>>> 
1

或者,如果你想除了最後一個偶數索引的元素:

print [data[i] for i in range(0,len(data)-1,2)] 
相關問題