所以我嘗試只打印月份,當(dāng)我使用:regex = r'([a-z]+) \d+'re.findall(regex, 'june 15')它打?。毫碌钱?dāng)我嘗試對這樣的列表執(zhí)行相同操作時:regex = re.compile(r'([a-z]+) \d+')l = ['june 15', 'march 10', 'july 4']filter(regex.findall, l)它打印了相同的列表,就像他們沒有考慮到我不想要這個數(shù)字的事實。
1 回答

尚方寶劍之說
TA貢獻1788條經(jīng)驗 獲得超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']]
獎金:
為了展平列表列表,您可以執(zhí)行以下操作:
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']
添加回答
舉報
0/150
提交
取消