You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过输入参数快速切换函数条件中的all与any判断?

优雅切换all/any判断的两种方案

这问题我之前也碰到过,重复写两段几乎一样的if-else确实冗余又不优雅,给你两个简洁的解决思路:

方案1:直接传入可调用的判断函数(最Pythonic)

你可以给check_function新增一个参数,直接接收all或any这类可调用对象,默认设为all,调用时就能灵活切换判断逻辑:

def check_function(some_input_parameters, check_func=all):
    # do_smth ...
    # 直接用传入的判断函数处理生成器表达式
    if check_func(bet_res[i] for i in res_number_list):
        good_row_list.append(row_dict)
    else:
        bad_row_list.append(row_dict)
    # do_smth ...

调用方式:

  • 需要all判断时:check_function(your_parameters)(用默认值即可)
  • 需要any判断时:check_function(your_parameters, check_func=any)

这种方式完全贴合Python的函数式编程风格,代码简洁可读性强,不需要额外的分支判断。

方案2:用字典映射字符串标志(兼容你原有的参数逻辑)

如果想保留原有的字符串标志(比如any_all_flag='all'或'any'),可以用字典把字符串映射到对应的判断函数,彻底消除重复代码块:

def check_function(some_input_parameters, any_all_flag='all'):
    # 定义字符串到判断函数的映射
    check_mapping = {'all': all, 'any': any}
    # 根据标志获取对应的判断函数
    check_func = check_mapping[any_all_flag]
    
    # do_smth ...
    if check_func(bet_res[i] for i in res_number_list):
        good_row_list.append(row_dict)
    else:
        bad_row_list.append(row_dict)
    # do_smth ...

原来的调用逻辑不用改动,但内部代码从两段重复的if-else简化成了一行映射,后续维护起来方便很多。

两种方案都能彻底消除冗余代码,让逻辑更清晰~

内容的提问来源于stack exchange,提问作者Ivan Fomin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:15:18