簡體   English   中英

python re.compile()和re.findall()

[英]python re.compile() and re.findall()

所以我嘗試只打印月份,當我使用時:

regex = r'([a-z]+) \d+'
re.findall(regex, 'june 15')

它打印:june但是當我嘗試為這樣的列表做同樣的事情時:

regex = re.compile(r'([a-z]+) \d+')
l = ['june 15', 'march 10', 'july 4']
filter(regex.findall, l)

它打印相同的列表,就像他們沒有考慮到我不想要這個數字的事實。

像這個例子一樣使用map而不是filter

import re

a = ['june 15', 'march 10', 'july 4']
regex = re.compile(r'([a-z]+) \d+')
# Or with a list comprehension
# output = [regex.findall(k) for k in a]
output = list(map(lambda x: regex.findall(x), a))
print(output)

輸出:

[['june'], ['march'], ['july']]

獎金:

為了壓縮列表列表,您可以執行以下操作:

output = [elm for k in a for elm in regex.findall(k)]
# Or:
# output = list(elm for k in map(lambda x: regex.findall(x), a) for elm in k)

print(output)

輸出:

['june', 'march', 'july']

暫無
暫無

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

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