0
我有一個字符串列表。我試圖找到匹配正則表達式模式的列表中的所有字符串。使用正則表達式的搜索列表
我在考慮用循環/列表理解/過濾來實現。
Similar to this post. (不過,我不是很明白什麼是該職位的r.match所以我就開始單獨的線程)。
import re
word_list = ['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1']
# start with letter C/D and then follow by digit
pattern = re.compile('^[CD]\d.*')
result_list = []
for word in word_list:
try:
result_list.append(re.findall(pattern, word)[0])
except:
pass
print word_list
print result_list
# OUTPUT >>
['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1']
['C3S3', 'D4D4']
誰能給我一個如何實現我的想法的一些提示使用列表解析或過濾器。
這就是我想要的東西。如果你可以打破Ln [3]並解釋它,那將是非常棒的! –
@ B.Mr.W。你可以在這裏找到解釋:http://docs.python.org/2/library/functions.html#filter – Kent