簡體   English   中英

在 functools.reduce 中使用 if else 語句

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM