Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何实现python';有自定义谓词的()吗?_Python_Python 2.7_Functional Programming_Any_Filterfunction - Fatal编程技术网

如何实现python';有自定义谓词的()吗?

如何实现python';有自定义谓词的()吗?,python,python-2.7,functional-programming,any,filterfunction,Python,Python 2.7,Functional Programming,Any,Filterfunction,我想改用它,但是any()只接受一个参数:iterable。有更好的方法吗?使用a作为参数: >>> l = list(range(10)) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> if filter(lambda x: x > 10, l): ... print "foo" ... else: # the list will be empty,

我想改用它,但是
any()
只接受一个参数:iterable。有更好的方法吗?

使用a作为参数:

>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> if filter(lambda x: x > 10, l):
...     print "foo"
... else:                     # the list will be empty, so bar will be printed
...     print "bar"
... 
bar
这里谓词位于生成器表达式的表达式端,但是您可以使用其中的任何表达式,包括使用函数

演示:

生成器表达式将被迭代,直到
any()
找到
True
结果,并且不再:

>>> l = range(10)
>>> any(x > 10 for x in l)
False
>>> l = range(20)
>>> any(x > 10 for x in l)
True

any()
中使用生成器表达式:

这假设您已经有了一些要使用的谓词函数,当然,如果是这样简单的函数,您可以直接使用布尔表达式:
any(i>10表示l中的i)

>>> l = range(10)
>>> any(x > 10 for x in l)
False
>>> l = range(20)
>>> any(x > 10 for x in l)
True
>>> from itertools import count
>>> endless_counter = count()
>>> any(x > 10 for x in endless_counter)
True
>>> # endless_counter last yielded 11, the first value over 10:
...
>>> next(endless_counter)
12
pred = lambda x: x > 10
if any(pred(i) for i in l):
    print "foo"
else:
    print "bar"