将列表分为两部分的好方法,条件是内部列表中的值

时间:2018-12-18 03:41:14

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

目标是从以下内容开始:

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而不是外部def
  2. 我该如何破坏lambda的参数
  3. 如何与and短路使用budget=-cost

一个不错的解决方案可能是:

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

and的方式使用short-circuit

1 个答案:

答案 0 :(得分:0)

一个简单的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)]