在本文中,我们将解释和使用Python中的谓词。
谓词
Predicate在一般意义上是关于某事的陈述,要么是真的,要么是假的。在编程中,谓词表示返回布尔值的单参数函数。
谓词简单示例
下面是一个使用谓词函数的简单示例。
#!/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
是一个简单的谓词,它对所有大于零的值返回真。
fres = filter(ispos, vals)
filter
函数将谓词作为其第一个参数。它返回满足条件的可迭代值。
print(list(fres))
我们使用list
内置函数将可迭代对象转换为列表。
$ ./simple.py [2, 7, 9, 2, 3, 1, 6]
任意谓词
可以使用lambda
创建匿名谓词。
#!/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列表理解。
#!/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
模块包含大量用于处理可迭代对象的函数。他们中的许多人接受谓词作为参数。
#!/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教程。