gpt4 book ai didi

python - 如何将 'if' 语句传递给函数?

转载 作者:太空狗 更新时间:2023-10-30 01:41:44 24 4
gpt4 key购买 nike

我想将可选的“if”语句传递给要执行的 Python 函数。例如,该函数可能会将一些文件从一个文件夹复制到另一个文件夹,但该函数可以采用可选条件。

因此,例如,对该方法的一次调用可以说“将文件从源复制到目标 if source.endswith(".exe")

下一个调用可能只是无条件地将文件从源复制到目标。

下一个调用可能是将文件从源复制到目标如果今天是星期一

如何将这些条件传递给 Python 中的函数?

最佳答案

函数是对象。它只是一个返回 bool 结果的函数。

def do_something( condition, argument ):
if condition(argument):
# whatever

def the_exe_rule( argument ):
return argument.endswith('.exe')

do_something( the_exe_rule, some_file )

Lambda 是另一种创建此类函数的方法

do_something( lambda x: x.endswith('.exe'), some_file )

关于python - 如何将 'if' 语句传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6665082/

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