在 Python 中移除虚假值

PythonPythonBeginner
立即练习

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

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

简介

在这个挑战中,你需要编写一个 Python 函数,用于从列表中移除虚假值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") 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") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-13605{{"在 Python 中移除虚假值"}} python/booleans -.-> lab-13605{{"在 Python 中移除虚假值"}} python/comments -.-> lab-13605{{"在 Python 中移除虚假值"}} python/lists -.-> lab-13605{{"在 Python 中移除虚假值"}} python/tuples -.-> lab-13605{{"在 Python 中移除虚假值"}} python/function_definition -.-> lab-13605{{"在 Python 中移除虚假值"}} python/build_in_functions -.-> lab-13605{{"在 Python 中移除虚假值"}} python/data_collections -.-> lab-13605{{"在 Python 中移除虚假值"}} end

压缩列表

编写一个函数 compact(lst),它接受一个列表作为参数,并返回一个移除了所有虚假值的新列表。虚假值包括 FalseNone0""

要解决这个问题,你可以使用 filter() 函数从列表中过滤掉虚假值。

def compact(lst):
  return list(filter(None, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) ## [ 1, 2, 3, 'a', 's', 34 ]

总结

在这个挑战中,你已经学会了如何使用 Python 中的 filter() 函数从列表中移除虚假值。