Lambda中的Python Try Catch Block [英] Python Try Catch Block inside lambda

查看:157
本文介绍了Lambda中的Python Try Catch Block的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在lambda函数内部使用try catch块.我需要lambda函数将某个变量转换为整数,但并非所有值都可以转换为整数.

Is it possible to use try catch block inside of a lambda function. I need the lambda function to convert a certain variable into an integer, but not all of the values will be able to be converted into integers.

推荐答案

不是. Python lambda只能是单个表达式.使用命名函数.

Nope. A Python lambda can only be a single expression. Use a named function.

编写用于转换类型的通用函数很方便:

It is convenient to write a generic function for converting types:

def tryconvert(value, default, *types):
    for t in types:
        try:
            return t(value)
        except (ValueError, TypeError):
            continue
    return default

然后您可以编写lambda:

Then you can write your lambda:

lambda v: tryconvert(v, 0, int)

您还可以编写tryconvert(),以便它返回一个采用要转换的值的函数;那么您就不需要lambda了:

You could also write tryconvert() so it returns a function that takes the value to be converted; then you don't need the lambda:

def tryconvert(default, *types):
    def convert(value):
        for t in types:
            try:
                return t(value)
            except (ValueError, TypeError):
                continue
        return default
    # set name of conversion function to something more useful
    namext = ("_%s_" % default) + "_".join(t.__name__ for t in types)
    if hasattr(convert, "__qualname__"): convert.__qualname__ += namext
    convert.__name__ += namext
    return convert

现在tryconvert(0, int)返回一个将值转换为整数的函数,如果无法完成,则返回0.

Now tryconvert(0, int) returns a function that takes a value and converts it to an integer, and returns 0 if this can't be done.

这篇关于Lambda中的Python Try Catch Block的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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