Skip to main content
 首页 » 编程设计

python : Calling functions from inside another function parameter

2025年05月04日12txw1958

我是 python 的新手,所以请原谅外行的描述。

问题:给定一个句子,返回一个单词颠倒的句子

我的解决方案:

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

输出:

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

代码按预期方式工作,但我的问题是,为什么我不能直接从前一个函数的返回结果进行函数调用。我,我

为什么我不能做类似的事情

返回 ' '.join(text.split().reverse())

这在 java 中工作得很好,因为我从 text.split() 得到 List 对象,我将使用 reverse() 函数对其进行操作,该函数将返回倒排列表,然后由 join( ) 将这个列表变成一个字符串。

这个,也是我试过的:

text.split() 返回一个列表,并在其上应用 .reverse() 函数应该以相反的顺序返回同一列表的元素,但是当我执行这一行时, print(text.split().reverse()),我得到 None

请您参考如下方法:

因为 reverse 返回 None,并更新列表,所以 None 对 join 无效。

是的,所以 reverse 是 inplace 函数,因此无法修复它。

所以使用反转:

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

或者[::-1]:

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

来自文档:

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