Problem : I want to improve my understanding of the python map function. I made a function which can return the lengths of words in a given phrase as a list. However, I would like to simply use the map function with a lambda function and pass in a string. Also, I am using python 3.
Current Function (WORKS) :
phrase = 'How long are the words in this phrase'
def word_lengths(phrase):
phrase = phrase.split(' ')
wordLengthList = []
for i in range(len(phrase)):
wordLengthList.append(len(phrase[i]))
return wordLengthList
word_lengths(phrase)
Current implementation of map (DOES NOT WORK):
list(map(lambda x: len(x.split(' ')), phrase))
If anyone could help me resolve this issue I would really appreciate it.
mapis a little outdated and you might be better off using a list comprehension or a generator expression. Plus personally I find them more readable.map(len, phrase.split(' '))? Hard to tell, because yourCurrent Function (WORKS)- actually doesn't (lstis undefined).list(map(lambda...instead of a list comprehension?