gpt4 book ai didi

python : Calling functions from inside another function parameter

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:32 24 4
gpt4 key购买 nike

我是 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 无效。

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

所以使用反转:

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

关于 python : Calling functions from inside another function parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52999854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com