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

Python中动态构建eval条件语句的实现方法

动态构建嵌套otherwise的eval语句

需求说明

给定一个包含n个预定义条件变量的列表(如[Condition1, Condition2, Condition3]),需严格按照列表顺序生成嵌套格式的eval语句:

  • 列表含1个元素:eval(Condition1)
  • 列表含2个元素:eval(Condition1).otherwise(eval(Condition2))
  • 列表含3个及以上元素:eval(Condition1).otherwise(eval(Condition2).otherwise(eval(Condition3)))(以此类推)

实现方案

可以通过Python字符串拼接逻辑动态生成目标语句,下面是封装好的函数实现:

def build_eval_statement(condition_list, default_value=None):
    # 处理空列表的边界情况
    if not condition_list:
        raise ValueError("条件列表不能为空")
    
    # 生成每个条件对应的eval片段
    eval_parts = [f"eval({cond})" for cond in condition_list]
    
    # 拼接嵌套的otherwise结构
    eval_statement = eval_parts[0]
    for part in eval_parts[1:]:
        eval_statement = f"{eval_statement}.otherwise({part})"
    
    # 如果传入默认值,追加到最后
    if default_value is not None:
        eval_statement = f"{eval_statement}.otherwise({repr(default_value)})"
    
    return eval_statement

使用示例

结合你提供的示例代码,调用方式如下:

from pyspark.sql.functions import col, when
# 预定义条件变量
Condition1 = "when(col('YearMonths') < 202306, 'SMALL')"
Condition2 = "when(col('YearMonths') > 202306, 'BIG')"

# 构建条件列表
condition_list = [Condition1, Condition2]
# 生成带默认值的eval语句
EVAL_ALL = build_eval_statement(condition_list, default_value='Nothing')

# 执行查询
display(df.select(col('YearMonths'), eval(EVAL_ALL)))

运行后,EVAL_ALL会被生成为:
"eval(Condition1).otherwise(eval(Condition2).otherwise('Nothing'))"

边界场景处理

  • 当列表仅含1个条件时:
    condition_list = [Condition1]
    EVAL_ALL = build_eval_statement(condition_list)
    # 生成结果:"eval(Condition1)"
    
  • 当列表含3个条件时:
    Condition3 = "when(col('YearMonths') == 202306, 'MEDIUM')"
    condition_list = [Condition1, Condition2, Condition3]
    EVAL_ALL = build_eval_statement(condition_list)
    # 生成结果:"eval(Condition1).otherwise(eval(Condition2).otherwise(eval(Condition3)))"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:06:06