[英]python re.compile() and re.findall()
So I try to print only the month, and when I use : 所以我尝试只打印月份,当我使用时:
regex = r'([a-z]+) \d+'
re.findall(regex, 'june 15')
And it prints : june But when I try to do the same for a list like this : 它打印:june但是当我尝试为这样的列表做同样的事情时:
regex = re.compile(r'([a-z]+) \d+')
l = ['june 15', 'march 10', 'july 4']
filter(regex.findall, l)
it prints the same list like they didn't take in count the fact that I don't want the number. 它打印相同的列表,就像他们没有考虑到我不想要这个数字的事实。
Use map
instead of filter
like this example: 像这个例子一样使用
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)
Output: 输出:
[['june'], ['march'], ['july']]
Bonus: 奖金:
In order to flatten the list of lists you can do: 为了压缩列表列表,您可以执行以下操作:
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)
Output: 输出:
['june', 'march', 'july']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.