【问题标题】:Good way of dividing a list of lists in two parts, conditional to the values in the inner list将列表列表分为两部分的好方法,以内部列表中的值为条件
【发布时间】:2019-05-18 11:02:09
【问题描述】:

目标是从以下开始:

budget = 100
projects = [('B', 60), ('A', 35), ('F', 35), ('G', 35), ('C', 20), ('E', 20), ('D', 10)]

并实现projects=[('B', 60), ('A', 35)]remainingBudget =5

作为一名 JS 程序员,我通过某种方式得到了以下工作:

def findProjectsThatFitTheBudget(budget, projects):
    # find the most expensive projects that fit the given budget, and note the budget that remains after allocations
    remainingBudget = budget

    def shoulIncludeProject(name, cost):
        nonlocal remainingBudget
        if(cost <= remainingBudget):
            remainingBudget -= cost
            return True
        return False
    projects = list(
        takewhile(lambda project: shoulIncludeProject(project[0], project[1]), projects))

    # we now have the projects we are working with, and also the budget that remains unallocated

我想知道最 Pythonic 的重构方式是什么?我至少坚持以下几点:

  1. 如何编写简单的 lambda 而不是外部定义
  2. 如何对 lambda 的参数进行解构
  3. 如何以短路方式使用andbudget=-cost

一个漂亮的解决方案可能是:

projects = list(
    takewhile(lambda name, cost: cost<= budget and budget=-cost, projects))

short-circuit 的方式使用and

【问题讨论】:

    标签: python python-3.x lambda destructuring short-circuiting


    【解决方案1】:

    一个简单的for 循环在预算用完时短路并没有错:

    viable_projects = []
    for project, cost in projects:
        budget -= cost
        if budget < 0:
            break
        viable_projects.append((project, cost))
    

    viable_projects 变为:

    [('B', 60), ('A', 35)]
    

    【讨论】:

    • 谢谢。对于 Python 来说仍然很冗长 :) 会让这个问题暂时悬而未决
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多