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

南笙酒味 提交于 2021-02-07 14:48:15

问题


I am Python newbie, and just become very interested in Lambda expression. The problem I have is to find one and only one target element from a list of elements with lambda filter. In theory, when the target element is found there is no sense to continue anymore.

With for loop it is pretty simple to break the loop, but what about by using lambda? is it after all possible to do this? I search from Google, but did not find the expected solution


回答1:


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

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

So in practice your lambda will not be applied to whole list unless you start getting elements from it. So if you Only request one item from this generator you will get your functionality.

@edit:

To request one object you'd call next(gen)

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

Would output 3 and not process anything past 3 in lst




回答2:


with just lambdas is no possible, you need either use filter (itertools.ifilter in python 2) or a conditional generation expression, and call next on that one to get the first element out of it

For example, let said you want the multiple of 5 in a list

>>> 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
>>>     


来源:https://stackoverflow.com/questions/39291336/is-it-possible-to-break-from-lambda-when-the-expected-result-is-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!