python中一行lambda函数中的条件语句? [英] Conditional statement in a one line lambda function in python?

查看:4721
本文介绍了python中一行lambda函数中的条件语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果以前曾经问过这个问题,但我无法在任何地方看到它。

Apologies if this has been asked before, but I couldn't see it anywhere.

基本上我遇到过一个我需要利用的场景lambda函数中的if语句。令人困难的是理想情况下它需要在一行代码中(如果可能的话?)

Essentially I've come across a scenario where i need to make use of an if statement inside a lambda function. What makes it difficult is that ideally it needs to be in a single line of code (if thats even possible?)

通常,我会这样写:

T = 250

if (T > 200):
    rate = 200*exp(-T)
else:
    rate = 400*exp(-T)

return (rate)

但是我需要它看起来像这样:

However i need it to look like this:

rate = lambda(T) : if (T>200): return(200*exp(-T)); else: return(400*exp(-T))

我意识到更容易做的事情就是在lambda函数之外做出决策,然后为每个case都有一个单独的lambda函数,但它不适合这里。 lambda函数存储在一个数组中,并在需要时访问,每个数组元素对应一个特定的速率,因此对于相同的速率有两个单独的行会弄乱。任何帮助将不胜感激,或如果不可能,其他人的一些确认将是不错的:)

I realize the easier thing to do would to take the decision making outside of the lambda functions, and then have a separate lambda function for each case, but its not really suitable here. The lambda functions are stored in an array and accessed when needed, with each array element corresponding to a particular "rate" so having two separate rows for the same "rate" would mess things up. Any help would be greatly appreciated, or if its not possible, some confirmation from others would be nice :)

推荐答案

使用 exp1如果cond else exp2 语法。

rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)

注意你不要在lambda表达式中使用 return

Note you don't use return in lambda expressions.

这篇关于python中一行lambda函数中的条件语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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