【问题标题】::How can I change this Python code to use map ,filter, and reduce so that it can produce result with as few code possible?:如何更改此 Python 代码以使用 map、filter 和 reduce,以便它可以用尽可能少的代码生成结果?
【发布时间】:2021-10-08 08:38:34
【问题描述】:

我有一个 Python 代码,我正在尝试使用 Python 函数式编程来减少可能的代码行数:

for t in text_from_file:
    separated_text = separate_data(t)
    employees.append(Employee(separated_text[1], separated_text[3], separated_text[7], float(separated_text[8])))

for e in employees:
    if e.hire_type == "FullTime":
        e.monthly_payout = e.salary
    elif e.hire_type == "Hourly":
        e.monthly_payout = e.salary * 0.5
    else:
        e.monthly_payout = e.salary * 0.25

    


for e in employees:
    year = datetime.strptime(e.start_date, '%d/%m/%Y').year
    if year > 1995:
        e.monthly_payout = e.monthly_payout * 0.85
        print(f"{e.full_name:<12} | Monthly payout | {e.monthly_payout:<8}")
        print("____________________________________")

如何使用 lambda、map、filter 和 reduce 转换这些代码?

【问题讨论】:

  • 不确定你在寻找什么 lambdas。但是你可以通过在一个循环中做所有事情而不是循环同样的事情 3 次来减少你当前的例子。

标签: python functional-programming


【解决方案1】:

函数式编程 (FP) 不一定会使您的程序更短,您也不一定需要使用 maplambda 等函数。我建议用类似的语言编写 FP 风格Python 更多的是关于构建代码(通常通过模块化,例如辅助函数),以便您可以更轻松地推断类型、副作用和正确性。

例如,您可以将您的第一个循环重写为(在 Python3 中使用类型注释):


def update_payout(e: Employee, default: float = 0.25) -> Employee:
    """Update employee monthly payout based on hire type."""
    if e.hire_type == "FullTime":
        e.monthly_payout = e.salary
    elif e.hire_type == "Hourly":
        e.monthly_payout = e.salary * 0.5
    else:
        e.monthly_payout = e.salary * default
    return e

employees = [update_payout(e) for e in employees]

请注意,添加了一个 default 多重参数,因为该函数现在可以在您的第二个循环中重用。对于您的第二个循环,您可以编写另一个列表推导,并将打印的 IO 活动分开。

emloyees_ = [update_payout(e, 0.85) for e in employees if 
             datetime.strptime(e.start_date, '%d/%m/%Y').year > 1995]

for e in employees_:
    print('your printing function...')

或者您也可以使用辅助函数重写第二个循环,然后只运行一个列表解析,如下所示:

employees = [update_post_1995(update_payout(e)) for e in employees]

链式函数非常实用,但请注意,在 Python 中,语法使其更难阅读,并且您真的想使用类型检查,例如mypy 如果你这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2019-06-04
    • 2021-07-25
    • 1970-01-01
    • 2011-11-03
    相关资源
    最近更新 更多