Lambda函数内部的python迭代过程 [英] python iterative process inside lambda function

查看:138
本文介绍了Lambda函数内部的python迭代过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的python 功能

I have a simple python function

def positiveGauss(mean,stdev):
        result = -1
        while result < 0:
                result = mean + np.random.randn()*stdev
        return result

是否可以使用 lambda 做同样的技巧?它需要在lambda内部进行迭代,但是我仍然相信这是可能的.

Is it possible to do the same trick using lambda? It requires to have iterations inside lambda, but I still believe it is possible.

推荐答案

出于多样性的考虑:

lambda m, s: next(x for x in (m + np.random.randn() * s for _ in iter(int, 1)) if x >= 0)

一种非递归解决方案,它利用了iter的两个参数形式和两个生成器表达式.

A non-recursive solution that takes advantage of the two-argument form of iter and two generator expressions.

iter(int, 1)调用int(),直到返回1,这根本不可能发生.因此内部生成器表达式

iter(int, 1) calls int() until it returns 1, which simply can't happen. Therefore the inner generator expression

(m + np.random.randn() * s for _ in iter(int, 1))

是一个生成器,可无限期评估并产生m + np.random.randn() * s.外部生成器表达式一一从内部表达式获取值,但仅产生等于或大于零的值.然后next函数从外部生成器获取第一个值,这是内部生成器与条件匹配得出的第一个值.

is a generator that evaluates and yields m + np.random.randn() * s indefinitely. The outer generator expression takes values from the inner expression one by one, but only yields values that are equal to or greater than zero. The next function then takes the first value from the outer generator, which is first value yielded by the inner generator matching the condition.

这篇关于Lambda函数内部的python迭代过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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