有没有一种方法可以执行"if"操作.在python的lambda中? [英] Is there a way to perform "if" in python's lambda?

查看:77
本文介绍了有没有一种方法可以执行"if"操作.在python的lambda中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.6 中,我想这样做:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

这显然不是语法.是否可以在 lambda 中执行 if ,如果可以的话该怎么做?

This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it?

推荐答案

您正在寻找的语法:

lambda x: True if x % 2 == 0 else False

但是您不能在lambda中使用 print raise .

But you can't use print or raise in a lambda.

这篇关于有没有一种方法可以执行"if"操作.在python的lambda中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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