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

Posted

技术标签:

【中文标题】将列表列表分为两部分的好方法,以内部列表中的值为条件【英文标题】: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 的重构方式是什么?我至少坚持以下几点:

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

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

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

short-circuit 的方式使用and

【问题讨论】:

【参考方案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 来说仍然很冗长 :) 会让这个问题暂时悬而未决

以上是关于将列表列表分为两部分的好方法,以内部列表中的值为条件的主要内容,如果未能解决你的问题,请参考以下文章

数据结构 - 选择排序

python - 如何首先根据初始列表的单个元素将列表拆分为子列表,然后在python中将列表的连续部分拆分为子列表?

SwiftUI 将部分列表固定到底部

css元素类型如何转换?

管理列表的好方法是什么?

如何将列表分成两部分?