问题描述
我想知道是否有一个原因是Python内置函数中没有第一个(可迭代的)
,有点类似于 any(可迭代)
和 all(可迭代)
(它可能藏在某个stdlib模块中,但我在<$ c $中看不到它C> itertools )。 首先
将执行短路发生器评估,以便可以避免不必要的(和可能无限数量的)操作; ie
I'm wondering if there's a reason that there's no first(iterable)
in the Python built-in functions, somewhat similar to any(iterable)
and all(iterable)
(it may be tucked in a stdlib module somewhere, but I don't see it in itertools
). first
would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.
def identity(item):
return item
def first(iterable, predicate=identity):
for item in iterable:
if predicate(item):
return item
raise ValueError('No satisfactory value found')
通过这种方式,您可以表达以下内容:
This way you can express things like:
denominators = (2, 3, 4, 5)
lcd = first(i for i in itertools.count(1)
if all(i % denominators == 0 for denominator in denominators))
显然你不能做 list(generator)[0 ]
在这种情况下,因为生成器没有终止。
Clearly you can't do list(generator)[0]
in that case, since the generator doesn't terminate.
或者如果你有一堆正则数据要匹配(当他们有用时)都具有相同的 groupdict
界面):
Or if you have a bunch of regexes to match against (useful when they all have the same groupdict
interface):
match = first(regex.match(big_text) for regex in regexes)
通过避免<$来节省大量不必要的处理C $ C>列表(generato r)[0] 并在正匹配时短路。
You save a lot of unnecessary processing by avoiding list(generator)[0]
and short-circuiting on a positive match.
推荐答案
如果你有一个迭代器,你可以调用它的 next
方法。类似于:
If you have an iterator, you can just call its next
method. Something like:
In [3]: (5*x for x in xrange(2,4)).next()
Out[3]: 10
这篇关于为什么Python中没有第一个(可迭代的)内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!