为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

阿晨1998 2021-09-11 19:33:08
所以我尝试只打印月份,当我使用:regex = r'([a-z]+) \d+'re.findall(regex, 'june 15')它打印:六月但是当我尝试对这样的列表执行相同操作时:regex = re.compile(r'([a-z]+) \d+')l = ['june 15', 'march 10', 'july 4']filter(regex.findall, l)它打印了相同的列表,就像他们没有考虑到我不想要这个数字的事实。
查看完整描述

1 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

使用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']


查看完整回答
反对 回复 2021-09-11
  • 1 回答
  • 0 关注
  • 273 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信