問題描述
我想知道 Python 內(nèi)置函數(shù)中沒有 first(iterable)
是否有原因,有點類似于 any(iterable)
和 all(iterable)
(它可能藏在某個 stdlib 模塊中,但我在 itertools
中看不到它).first
將執(zhí)行短路生成器評估,從而可以避免不必要的(并且可能是無限數(shù)量的)操作;即
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')
這樣你可以表達如下內(nèi)容:
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))
顯然你不能在這種情況下執(zhí)行 list(generator)[0]
,因為生成器不會終止.
Clearly you can't do list(generator)[0]
in that case, since the generator doesn't terminate.
或者,如果您有一堆正則表達式要匹配(當(dāng)它們都具有相同的 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)
通過避免 list(generator)[0]
和在正匹配時短路,您可以節(jié)省大量不必要的處理.
You save a lot of unnecessary processing by avoiding list(generator)[0]
and short-circuiting on a positive match.
推薦答案
如果你有一個迭代器,你可以調(diào)用它的 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
這篇關(guān)于為什么 Python 中沒有 first(iterable) 內(nèi)置函數(shù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!