首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python re.compile()和re.findall()

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

Stack Overflow用户
提问于 2018-12-10 00:02:23
回答 1查看 4.4K关注 0票数 1

因此,我尝试只打印月份,当我使用:

代码语言:javascript
复制
regex = r'([a-z]+) \d+'
re.findall(regex, 'june 15')

它打印:六月,但是当我试图对这样的列表做同样的事情时:

代码语言:javascript
复制
regex = re.compile(r'([a-z]+) \d+')
l = ['june 15', 'march 10', 'july 4']
filter(regex.findall, l)

它打印相同的列表,就像他们没有把我不想要的数字计算在内。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-10 00:10:37

使用map而不是filter,如下例所示:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
[['june'], ['march'], ['july']]

奖金:

为了简化列表列表,可以这样做:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
['june', 'march', 'july']
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53697934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档