Is it possible to break into lambda when the expected result is found

I am new to Python and just really interested in lambda expression. The problem is to find one and only one target element from the list of elements with lambda filter. Theoretically, when the target element is found, there is no point in continuing anymore.

With a for looppretty simple breakloop, but what about using lambda? Is it really possible? I am searching from Google but have not found the expected solution

+4
source share
2 answers

From https://docs.python.org/3/library/functions.html#filter

Note that it is filter(function, iterable)equivalent to a generator (item for item in iterable if function(item)), None (item for item in iterable if item), None.

, , . , , .

@edit:

, next(gen)

lst = [1,2,3,4,5]
print(next(filter(lambda x: x%3==0, lst)))

3 3 lst

+2

lambdas , filter (itertools.ifilter python 2) , next,

, , ,

>>> test=[1,2,3,6,58,78,50,65,36,79,100]
>>> next( filter(lambda x:x%5==0,test) )
50
>>> next( x for x in test if x%5==0 )
50
>>>     
0

Source: https://habr.com/ru/post/1653433/


All Articles