[英]Using if else statement inside functools.reduce
我创建了一个运行良好的 function,但是,我想在 function.reduce 中添加 if else 语句,我不确定这是否可以实现。 尝试研究 func.reduce 但没有任何信息/用例可用于说明我希望 function 如何工作。 如果这在 python 中可行,或者我应该在另一种方法上使用 go,则需要一些建议。
我已经创建了这个 function,它按预期工作,'
def tempJoin(df,targetField,targetTitle,condition,targetResult,otherwise,show=False,lowercase=False):
case_conditions = list(zip(condition, targetResult))
product_col = functools.reduce(
lambda acc, x: acc.when(col(targetField).like(x[0]), F.lit(x[1])),case_conditions,F,).otherwise(otherwise)
df = df.withColumn(targetTitle, product_col)
if show:
df.show(10)
return df;
我完全知道我可以用这种方法 go ,但我觉得这可以进一步优化
def tempJoin(df,targetField,targetTitle,condition,targetResult,otherwise,show=False,lowercase=False):
case_conditions = list(zip(condition, targetResult))
if lowercase :
product_col = functools.reduce(
lambda acc, x: acc.when(lower(col(targetField)).like(x[0]), F.lit(x[1])),case_conditions,F,).otherwise(otherwise)
else :
product_col = functools.reduce(
lambda acc, x: acc.when(col(targetField).like(x[0]), F.lit(x[1])),case_conditions,F,).otherwise(otherwise)
df = df.withColumn(targetTitle, product_col)
if show:
df.show(10)
return df;
我想要实现的是添加 if else of 'lowercase=True',它将在 functools 本身内触发。 如下所示
product_col = functools.reduce(
if lowercase:
lambda acc, x: acc.when(lower(col(targetField)).like(x[0]), F.lit(x[1])),case_conditions,F,).otherwise(otherwise)
else:
lambda acc, x: acc.when(col(targetField).like(x[0]), F.lit(x[1])),case_conditions,F,).otherwise(otherwise)
这是可以实现的吗?
因此,您正在寻找“内联” if 语句? Python 调用这些条件表达式。
一般语法是some_value if condition else other_value
所以你的代码是:
product_col = functools.reduce(lambda ... if lowercase else lambda ...)
您可以将三元表达式放在when
子句中:
product_col = functools.reduce(
lambda acc, x:
acc.when(
(lower(col(targetField)) if lowercase else col(targetField)).like(x[0]),
F.lit(x[1])
), case_conditions, F
).otherwise(otherwise)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.