從匹配條件的迭代器中獲取第一項。我想從符合條件的列表中獲得第一項。重要的是,生成的方法不能處理整個列表,這可能相當大。例如,以下功能就足夠了:def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):
return i這個函數可以使用如下所示:>>> first(range(10))0>>> first(range(10), lambda i: i > 3)4然而,我想不出一個好的內置/一個班輪讓我這樣做。如果沒有必要的話,我不特別想復制這個函數。是否有一個內置的方式,以獲得第一個項目匹配的條件?
3 回答

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
作為一個可重用、文檔化和測試的功能
def first(iterable, condition = lambda x: True): """ Returns the first item in the `iterable` that satisfies the `condition`. If the condition is not given, returns the first item of the iterable. Raises `StopIteration` if no item satysfing the condition is found. >>> first( (1,2,3), condition=lambda x: x % 2 == 0) 2 >>> first(range(3, 100)) 3 >>> first( () ) Traceback (most recent call last): ... StopIteration """ return next(x for x in iterable if condition(x))
添加回答
舉報
0/150
提交
取消