一种很好的方法,可以根据内部列表中的值将列表分为两部分

2024-10-08 19:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是从以下几点开始:

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

我想知道什么是重构这一点最python的方式?我至少被以下几点困住了:

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

一个很好的解决方案可能是:

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

short-circuit的方式使用and


Tags: andthelambdanameprojectreturnthatdef
1条回答
网友
1楼 · 发布于 2024-10-08 19:29:35

预算耗尽时短路的简单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)]

相关问题 更多 >

    热门问题