Python Forum

Full Version: Please help to the beginer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
I am struggling with making
this code:

text = open('input.txt', 'r', encoding='utf8')
for i in text.readlines():
    print(re.findall('\S+e\S+', i))
to be functional:

text = open('input.txt', 'r', encoding='utf8')
map(lambda i: print(re.findall('[0-9]+', i)), text.readlines())
I can't understand why it doesn't work
Please advise,
Thanks
What version of Python are you using? Can you define "doesn't work"? And can you reproduce your problem without using files?
Hi micseydel,
python version is 3.5
Saying it doesn't work I mean I get no output after running "functionalized" code.
Same result when using a list instead of a file:
map(lambda z: print(re.findall('\S+e\S+', z)), ['asdf', 'asdfwert'])
No output

Thanks
Ok where to start...

When you use map() in Python 3, you don't just get a list back. You get back an object which you can iterator over which evaluated the elements lazily. You can force evaluation like so
for _ in map(lambda z: print(re.findall('\S+e\S+', z)), ['asdf', 'asdfwert']): pass
or
list(map(lambda z: print(re.findall('\S+e\S+', z)), ['asdf', 'asdfwert']))
Both of these bits of code iterate through the map() result, thereby forcing the evaluation which causes the print() calls.

That said, neither of these solutions would be considered good, and having a side-effect (e.g. print) in "functional" code like that (in the map) is unusual, I would say defeats some of the purpose of functional style.

You could instead do this
print('\n'.join(map(lambda z: str(re.findall('\S+e\S+', z)), ['asdf', 'asdfwert'])))
however Python programmers usually use comprehensions instead of map() (and filter()) like this
print('\n'.join(str(re.findall('\S+e\S+', z)) for z in ['asdf', 'asdfwert']))
Personally, I find the comprehension more readable in Python. I suggest this over "functional" code, in Python.

(For some context - I write functional code in Scala at work. I like Scala's map, filter, etc. because they're methods which you typically write out one line at a time rather than in Python which requires some awkward nesting. I like FP, but don't think it fits Python well enough.)
micseydel,
thank you a lot