测试列表中的每个元素是否都为假值

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,我们可以使用 all() 函数来检查列表中的所有元素是否都为真值。但如果我们想检查列表中的每个元素是否都为假值呢?在这个挑战中,你需要创建一个函数来检查列表中的每个元素是否都为假值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/booleans -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/comments -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/for_loops -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/lists -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/tuples -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/function_definition -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/default_arguments -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/lambda_functions -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} python/build_in_functions -.-> lab-13699{{"测试列表中的每个元素是否都为假值"}} end

测试列表中的每个元素是否都为假值

编写一个名为 none(lst, fn = lambda x: x) 的 Python 函数,该函数接受一个列表 lst 和一个可选函数 fn 作为参数。如果列表中的每个元素都为假值,则该函数应返回 True,否则返回 False。如果提供了可选函数 fn,则应使用它来确定列表中每个元素的真值。

要确定一个元素是否为假值,可以使用与 Python 的 bool() 函数相同的规则。一般来说,以下值被视为假值:

  • False
  • None
  • 0(整数)
  • 0.0(浮点数)
  • ''(空字符串)
  • [](空列表)
  • {}(空字典)
  • ()(空元组)
  • set()(空集合)

如果提供了可选函数 fn,它应接受一个参数并返回一个布尔值。该函数将对列表中的每个元素调用,并使用返回值来确定元素的真值。

def none(lst, fn = lambda x: x):
  return all(not fn(x) for x in lst)
none([0, 1, 2, 0], lambda x: x >= 2 ) ## False
none([0, 0, 0]) ## True

总结

在这个挑战中,你学习了如何创建一个 Python 函数来检查列表中的每个元素是否都为假值。你还学习了如何使用一个可选函数来确定列表中每个元素的真值。