python re.compile()和re.findall()
因此,我尝试只打印月份,当我使用:python re.compile()和re.findall(),python,regex,Python,Regex,因此,我尝试只打印月份,当我使用: 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) 它打印相同的列表,就像他们没有计算我不想要这个数字一样。使用map而不是filter,例如: imp
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)
它打印相同的列表,就像他们没有计算我不想要这个数字一样。使用
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']]
['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']]
['june', 'march', 'july']
使用
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']]
['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']]
['june', 'march', 'july']
如果bool(condition)=True列表中的所有项目都匹配,则筛选器保留整个内容,因此如果每个元素只有一个日期,则使用[re.sub(regex,'\\1',x)表示l中的x]如果bool(condition)=True列表中的所有项目匹配,则筛选器保留整个内容,因此如果每个元素只有一个日期,则使用[re.sub(regex,'\\1',x)表示l中的x]或者只是一个列表理解:
output=[regex.findall(x)for x in a]
Great!!但是现在我把所有的月份都列在了一个列表里。我如何处理它并将它们放在一个简单的列表中呢?或者只是一个列表理解:output=[regex.findall(x)for x in a]
Great!!但是现在我把所有的月份都列在了一个列表里。我如何处理它并将它们放在一个简单的列表中?