在 Python 中根据筛选条件拆分列表

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,我们可以根据给定的筛选条件将一个列表拆分为两组。这可以通过列表推导式和 zip() 函数来完成。在这个挑战中,你将被要求编写一个函数,该函数接受一个列表和一个筛选条件作为输入,并返回两个列表,一个包含通过筛选条件的元素,另一个包含未通过筛选条件的元素。


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/booleans("Booleans") 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/build_in_functions("Build-in Functions") subgraph Lab Skills python/booleans -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/comments -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/conditional_statements -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/for_loops -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/list_comprehensions -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/lists -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/tuples -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/function_definition -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} python/build_in_functions -.-> lab-13591{{"在 Python 中根据筛选条件拆分列表"}} end

对列表进行二分

编写一个函数 bifurcate(lst, filter),它接受一个列表 lst 和一个筛选条件 filter 作为输入,并返回一个包含两个列表的列表。第一个列表应包含 lst 中通过筛选条件的元素,第二个列表应包含未通过筛选条件的元素。

要实现这个函数,你可以使用列表推导式和 zip() 函数。zip() 函数接受两个或更多列表作为输入,并返回一个元组列表,其中每个元组包含来自每个列表的对应元素。例如,zip([1, 2, 3], [4, 5, 6]) 返回 [(1, 4), (2, 5), (3, 6)]

你可以使用这个函数同时遍历 lstfilter,并根据元素是否通过筛选条件将它们添加到相应的列表中。

def bifurcate(lst, filter):
  return [
    [x for x, flag in zip(lst, filter) if flag],
    [x for x, flag in zip(lst, filter) if not flag]
  ]
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
## [ ['beep', 'boop', 'bar'], ['foo'] ]

总结

在这个挑战中,你学习了如何根据给定的筛选条件将一个列表拆分为两组。你使用了列表推导式和 zip() 函数来同时遍历列表和筛选条件,并根据元素是否通过筛选条件将它们添加到相应的列表中。