簡體   English   中英

使用正則表達式過濾數據列表的Pythonic方法?

[英]Pythonic way to filter a list of data with a regex?

我有一個字符串列表,我想用正則表達式過濾。 我有一個解決方案的開端:

lines = ['Some data', 'Data of interest', 'Some data', 'Data of Interest', 'Some data', 'Data of interest']
r = re.compile(r'.*[iI]nterest.*')
relevant_lines = [r.findall(line) for line in lines]
print(relevant_lines)

......幾乎有效:

[[], ['Data of interest'], [], ['Data of Interest'], [], ['Data of interest']]

...但是有沒有辦法只用匹配和沒有嵌套列表的行填充結果列表?

編輯 - 是否有比以下更清潔的方式?

[r[0] for r in [r.findall(line) for line in lines] if len(r) > 0]

只需使用普通循環,並非所有內容都適合列表comp:

r = re.compile(r'.*[iI]nterest.*')
relevant_lines = []
for line in lines:
    mtch = r.match(line)
    if mtch:
        relevant_lines.append(mtch.group())

如果你使用列表comp,生成器表達式和過濾空列表會更好:

relevant_lines = filter(None,(r.findall(line) for line in lines))

或者確實過濾匹配:

[x.group() for x in filter(None,(r.match(line) for line in lines))]

對於python2,使用itertools.ifilter

或者使用python2為itertools.imap切換映射並使用ifilter過濾更實用的方法:

[x.group() for x in filter(None, map(r.match, lines))]

您可以使用內部循環的生成器表達式重寫您自己的列表comp:

[r[0] for r in (r.findall(line) for line in lines) if r]

如果您不需要列表,請使用生成器表達式並迭代它。

relevant_lines = [m.group(0) for m in map(r.match, lines) if m is not None]

這是控制台的結果:

>>> import re
>>> lines = ['Some data', 'Data of interest', 'Some data', 'Data of Interest', 'Some data', 'Data of interest']
>>> r = re.compile(r'.*[iI]nterest.*')
>>> relevant_lines = [m.group(0) for m in map(r.match, lines) if m is not None]
>>> relevant_lines
['Data of interest', 'Data of Interest', 'Data of interest']

事情並不復雜。 將函數式編程與生成器結合起來非常好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM