简体   繁体   English

我可以编写lambda函数引发异常吗?

[英]Can I write a lambda function to raise an exception?

Suppose I have the following python list: 假设我有以下python列表:

my_list = [1, 2,'X', 'Y', 0]

Suppose I want to copy values of this list into a new list as follows: 假设我要将此列表的值复制到新列表中,如下所示:

  1. If it is a digit between 0-9, copy that value into the new list 如果它是介于0到9之间的数字,则将该值复制到新列表中
  2. ElIf it is 'X', copy None into the new list El如果是“ X”,则将“ None ”复制到新列表中
  3. Else raise an Exception 否则引发例外

Can I do it with a lambda function as shown below? 我可以使用如下所示的lambda函数来执行此操作吗? If so, how? 如果是这样,怎么办?

new_list = map(lambda(x): something-here-but-what??, my_list)

Why not just write a function that does what you want and put it in the lambda? 为什么不只是编写一个您想要的函数并将其放入lambda中呢? I don't see a reason to try to make a convoluted one-liner for something that should be more than one line. 我看不出有理由为一条不止一排的东西制作复杂的单线纸。

my_list = [1, 2,'X', 'Y', 0]

def replace(x):
    if x == 'X':
        return None
    elif type(x) == int and x <= 9 and x >= 0:
        return x
    else:
        raise ValueError('Bad value')

new_list = map(lambda(x): replace(x), my_list[:-2]) # Returns [1, 2, None]
new_list = map(lambda(x): replace(x), my_list) # Raises exception

To back up Brenden's (quite correct) answer... 要备份布伦登(相当正确)的答案...

You can actually do some weird things with Python ternary expressions... but the result is just unbearable. 实际上,您可以使用Python三元表达式来做一些奇怪的事情……但是结果是难以忍受的。 Consider a partial solution: 考虑部分解决方案:

>>> new_list = map(lambda x: x if isinstance(x, int) and (0 <= x and x <= 9) else ValueError('Bad things happened'), [1, 2, 3, "blah"])
>>> list(new_list)
[1, 2, 3, ValueError('Bad things happened',)]

Not only is that horrid and would probably confuse most Pythonistas (not just the use of an unusual construction, but why would you use this construction?), I don't know quite what to do yet about actually raising the exception right there without redefining the way list() works. 这不仅令人恐惧,而且可能会使大多数Pythonista迷惑(不仅是使用不寻常的构造,还为什么要使用这种构造?),我还不知道该如何在不重新定义的情况下实际引发异常呢? list()工作方式。 ( raise only works when it is standing alone.) raise当独自站在只有作品。)

So now we have a confusing lambda that conditionally permits a member into the new map construction or includes a ValueError object instead. 因此,现在我们有了一个令人困惑的lambda,该lambda有条件地允许成员进入新的地图构造或包含ValueError对象。 Yuk. 育。

Much better to abstract this whole idea away behind a function that does, in a very simple way, exactly what you want -- and let the "beautiful code part" be the bit people will normally need to read in the future that goes something like: 更好地将整个想法抽象成一个功能,该功能以一种非常简单的方式准确地实现了您想要的功能,并且让“美丽的代码部分”成为人们将来通常需要阅读的,类似于:

new_list = valid_list_to_map(your_list)

Use a conditional expression. 使用条件表达式。

a = list(map(lambda n: n if n in (0,1,2,3,4,5,6,7,8,9) else (None if n == 'X' else 1/0), my_list))

Other exceptions that can be raised: 可以引发的其他异常:
In the conditional expression replace 1/0 with 在条件表达式中,将1/0替换为

{}[n]                                       #KeyError
x                                           #NameError 
(_ for _ in ()).throw(Exception('Foo')))    #any kind of exception you want
int('x')                                    #ValueError

To raise an exception you have to use 'try' and 'except' statement and Statements are not allowed in the lambda expression. 要引发异常,您必须使用“ try”和“ except”语句,并且lambda表达式中不允许使用语句。 In the Lambda expression, you can only have expressions so you can't raise the exception in the lambda function. 在Lambda表达式中,只能包含表达式,因此不能在lambda函数中引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM