Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please help to the beginer
#1
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
Reply
#2
What version of Python are you using? Can you define "doesn't work"? And can you reproduce your problem without using files?
Reply
#3
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
Reply
#4
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.)
Reply
#5
micseydel,
thank you a lot
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python for beginer triluan 2 2,378 Mar-03-2019, 12:40 PM
Last Post: triluan
  Need Help with Start-up (DIY Beginer) Styles4gh 2 2,465 Mar-09-2018, 02:06 AM
Last Post: Larz60+
  help for beginer libed 3 4,611 Nov-11-2016, 04:34 AM
Last Post: Blue Dog
  beginer oop help noissue 7 6,855 Oct-12-2016, 03:45 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020