Python 谓词
最后修改于 2024 年 1 月 29 日
在本文中,我们解释并使用 Python 中的谓词。
谓词
谓词 的一般含义是指关于某事物的陈述,该事物要么为真,要么为假。在编程中,谓词表示返回布尔值的单参数函数。
谓词简单示例
以下是使用谓词函数的简单示例。
simple.py
#!/usr/bin/python def ispos(n): return n > 0 vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6] fres = filter(ispos, vals) print(list(fres))
我们有一个值列表。使用 `filter` 函数,我们过滤掉正数。
def ispos(n): return n > 0
`ispos` 是一个简单的谓词,它对所有大于零的值返回 true。
fres = filter(ispos, vals)
`filter` 函数将谓词作为其第一个参数。它返回一个满足条件的值的可迭代对象。
print(list(fres))
我们使用 `list` 内置函数将可迭代对象转换为列表。
$ ./simple.py [2, 7, 9, 2, 3, 1, 6]
匿名谓词
可以使用 `lambda` 创建匿名谓词。
anon.py
#!/usr/bin/python vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6] fres = filter(lambda e: e < 0, vals) print(list(fres))
在示例中,我们使用 lambda 函数过滤掉所有负数元素。
$ ./anon.py [-3, -1, -4]
Python 列表推导式谓词
谓词可以在 Python 列表推导式中使用。
list_com.py
#!/usr/bin/python def is_vowel(c): vowels = 'aeiou' if c in vowels: return True else: return False sentence = 'There are eagles in the sky.' vowels = [c for c in sentence if is_vowel(c)] print(vowels)
该示例从句子中过滤掉所有元音字母。
def is_vowel(c): vowels = 'aeiou' if c in vowels: return True else: return False
该函数是一个谓词。它为元音字符返回 True。
vowels = [c for c in sentence if is_vowel(c)]
if 条件的逻辑委托给 `is_vowel` 谓词。
$ ./list_com.py ['e', 'e', 'a', 'e', 'e', 'a', 'e', 'i', 'e']
带 more_itertools 的谓词
外部 `more_itertools` 模块包含许多用于处理可迭代对象的功能。其中许多接受谓词作为参数。
simple.py
#!/usr/bin/python from more_itertools import locate def pfn(n): return n > 0 and n % 2 == 0 vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6] idx = list(locate(vals, pfn)) vals2 = [vals[e] for e in idx] print(vals2)
该示例使用 `locate` 函数查找满足给定条件的所有值;在我们的例子中,是大于零且能被二整除的值。
idx = list(locate(vals, pfn))
我们将值和谓词函数作为参数传递给 `locate`。
vals2 = [vals[e] for e in idx]
由于该函数返回索引,我们使用列表推导式将它们转换为值。
$ ./locate.py [2, 2, 6]
来源
在本文中,我们使用了 Python 中的谓词。
作者
列出所有 Python 教程。