Please help to the beginer - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Please help to the beginer (/thread-17040.html) |
Please help to the beginer - polo - Mar-26-2019 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 RE: Please help to the beginer - micseydel - Mar-26-2019 What version of Python are you using? Can you define "doesn't work"? And can you reproduce your problem without using files? RE: Please help to the beginer - polo - Mar-26-2019 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 RE: Please help to the beginer - micseydel - Mar-26-2019 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']): passor 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.) RE: Please help to the beginer - polo - Mar-27-2019 micseydel, thank you a lot |