字典属性上的谓词函数

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/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") subgraph Lab Skills python/booleans -.-> lab-13599{{"字典属性上的谓词函数"}} python/comments -.-> lab-13599{{"字典属性上的谓词函数"}} python/lists -.-> lab-13599{{"字典属性上的谓词函数"}} python/tuples -.-> lab-13599{{"字典属性上的谓词函数"}} python/dictionaries -.-> lab-13599{{"字典属性上的谓词函数"}} python/function_definition -.-> lab-13599{{"字典属性上的谓词函数"}} python/lambda_functions -.-> lab-13599{{"字典属性上的谓词函数"}} end

检查属性

创建一个名为 check_prop 的函数,它接受两个参数:fnpropfn 参数是一个谓词函数,将应用于字典的指定属性。prop 参数是一个字符串,表示谓词函数将应用于的属性名称。

check_prop 函数应返回一个 lambda 函数,该函数接受一个字典,并将谓词函数 fn 应用于指定的属性。

def check_prop(fn, prop):
  return lambda obj: fn(obj[prop])
check_age = check_prop(lambda x: x >= 18, 'age')
user = {'name': 'Mark', 'age': 18}
check_age(user) ## True

总结

在这个挑战中,你学习了如何创建一个将谓词函数应用于字典指定属性的函数。在我们需要检查字典的特定属性是否满足某个条件的场景中,这会很有用。