本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

Python函数之间如何实现交互?

网络教程 app 1℃

Python函数之间如何实现交互

python 函数交互:零基础小白的常见疑惑

作为一名刚接触 python 函数的文科生,您可能会遇到一些困惑。例如,您不禁会问,不同的函数之间是否可以相互作用?

为了探讨这个问题,让我们 examine 下面的一段代码:

def make_great(names): for name in names: name_1 = "the great " + name.title() print(name_1)def show_magicians(names): for name in names: print(name.title())names = ["a", "b", "c", "tutu", "mumu"]make_great(names)show_magicians(names)

按照这种写法,您可能会希望通过第一个函数 make_great 修改列表 names,然后再在第二个函数 show_magicians 中显示修改后的列表。

答案:使用 map 函数

要实现在函数之间传递返回值,您可以利用 map 函数。map 函数将一个函数应用于可迭代对象的每个元素,并返回一个包含结果的新可迭代对象。

修改后的代码如下:

def make_great(names): return map(lambda name: "the Great " + name.title(), names)def show_magicians(names): for name in names: print(name.title())names = ["A", "b", "c", "tutu", "mumu"]show_magicians(make_great(names))

通过将 make_great 函数的返回值作为 show_magicians 函数的参数,我们实现了函数之间的交互。

以上就是Python 函数之间如何实现交互?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » Python函数之间如何实现交互?

喜欢 (0)