简体   繁体   中英

Python : Calling functions from inside another function parameter

I'm new to python so please excuse the layman description.

Question : Given a sentence, return a sentence with the words reversed

My Solution:

def sentence_reverse(text):
    a = text.split()
    a.reverse()
    return ' '.join(a)

Output:

sentence_reverse('I am home') --> 'home am I'
sentence_reverse('We are ready') --> 'ready are We'

the code works the way it is supposed to but my question is, why can't i make a function call directly from the returned result of the previous function. i,e

why can i not do something like

return ' '.join(text.split().reverse())

this would work just fine in java since i get List object from text.split() to which, i would operate on with the reverse() function which would return me the inverted list which would then be used by the join() to make this list into a string.

This, is also something that i have tried:

text.split() returns a List, and applying .reverse() function on it SHOULD return the elements of the same list in reverse order, but when i execute this line, print(text.split().reverse()) , i get None

Because reverse returns None, and updates the list, so so None is not valid for join .

Yeah so reverse is inplace function so no way to fix that.

So Use reversed :

return ' '.join(reversed(text.split()))

Or [::-1] :

return ' '.join(text.split()[::-1])

From docs:

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.


After code example.

https://docs.python.org/3/tutorial/datastructures.html

which would return me the inverted list ..

Here's the problem. In Python, calling list.reverse() doesn't return the reversed list. It just reverses it in place.

What you need is:

return " ".join(text.split()[::-1])

Instead of using .reverse You can use python list iterator to reverse:

me = 'ready are We'
" ".join(me.split()[::-1])
>>> 'We are ready'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM