1

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 :

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.

tripleee
  • 158,107
  • 27
  • 234
  • 292
Senseikaii
  • 67
  • 1
  • 9

1 Answers1

4

Use map instead of filter like this example:

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']
Chiheb Nexus
  • 8,494
  • 4
  • 28
  • 42
  • 1
    Or just a list comprehension: `output = [regex.findall(x) for x in a]` – larsks Dec 10 '18 at 00:13
  • 1
    Great !! But now I have all the month in a list inside a list. How can I deal with it and put them in a simple list instead ? – Senseikaii Dec 10 '18 at 00:14