根据函数对列表进行二分

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个挑战中,你将编写一个 Python 函数,该函数根据给定过滤函数的结果将列表拆分为两组。这是编程中的一项常见任务,尤其是在处理大型数据集时。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") subgraph Lab Skills python/comments -.-> lab-13590{{"根据函数对列表进行二分"}} python/conditional_statements -.-> lab-13590{{"根据函数对列表进行二分"}} python/for_loops -.-> lab-13590{{"根据函数对列表进行二分"}} python/list_comprehensions -.-> lab-13590{{"根据函数对列表进行二分"}} python/lists -.-> lab-13590{{"根据函数对列表进行二分"}} python/tuples -.-> lab-13590{{"根据函数对列表进行二分"}} python/function_definition -.-> lab-13590{{"根据函数对列表进行二分"}} python/lambda_functions -.-> lab-13590{{"根据函数对列表进行二分"}} end

根据函数对列表进行二分

编写一个函数 bifurcate_by(lst, fn),它接受一个列表 lst 和一个过滤函数 fn 作为参数。该函数应根据过滤函数的结果将列表拆分为两组。如果过滤函数对某个元素返回真值,则应将其添加到第一组。否则,应将其添加到第二组。

你的函数应返回一个包含两个列表的列表,其中第一个列表包含过滤函数返回真值的所有元素,第二个列表包含过滤函数返回假值的所有元素。

使用列表推导式根据 fn 对每个元素返回的值将元素添加到相应的组中。

def bifurcate_by(lst, fn):
  return [
    [x for x in lst if fn(x)],
    [x for x in lst if not fn(x)]
  ]
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
## [ ['beep', 'boop', 'bar'], ['foo'] ]

总结

在这个挑战中,你学习了如何根据给定过滤函数的结果将列表拆分为两组。你使用列表推导式,根据过滤函数对每个元素返回的值将元素添加到相应的组中。这是编程中的一项实用技术,尤其是在处理大型数据集时。