找到预期结果时是否有可能脱离lambda [英] Is it possible to break from lambda when the expected result is found

查看:64
本文介绍了找到预期结果时是否有可能脱离lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python新手,对Lambda表达式非常感兴趣.我的问题是从具有lambda过滤器的元素列表中找到一个且只有一个目标元素.从理论上讲,当找到目标元素时,就不再有继续存在的意义.

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.

使用for loop,对break循环非常简单,但是使用lambda怎么办?毕竟有可能做到这一点吗?我从Google搜索,但没有找到所需的解决方案

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

推荐答案

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

请注意,filter(function, iterable)等同于生成器 表达式(item for item in iterable if function(item)) if函数 不是None(item for item in iterable if item)(如果函数为 None.

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.

因此,实际上,除非您开始从其中获取元素,否则您的lambda不会应用于整个列表.因此,如果您仅从该生成器中请求一项,那么您将获得功能.

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:

要请求一个对象,您可以调用next(gen)

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

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

将输出3,并且不处理lst

这篇关于找到预期结果时是否有可能脱离lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆