lambda 参数解包错误 [英] lambda arguments unpack error

查看:16
本文介绍了lambda 参数解包错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2 中这段代码没问题:

In Python 2 this code is OK:

f = lambda (m, k): m + k

m = [1,2,3,4]
k = [5,6,7,8]

print(map(f, zip(m, k)))

但在 Python 3 中出现以下错误:

but in Python 3 the following error occurred:

f = lambda (m, k): m + k
^
SyntaxError: invalid syntax

如果我删除 lambda 表达式中的括号,则会发生另一个错误:

If I remove parentheses in lambda expression then another error occurred:

TypeError: <lambda>() missing 1 required positional argument: 'k'

将元组作为单个 lambda 参数的方法也适用于 Python 3,但不清楚(难以阅读):

Also approach with tuple as single lambda argument works in Python 3, but it's not clear (hard for reading):

f = lambda args: args[0] + args[1]

如何在 Python 3 中以正确的方式解压值?

How can I unpack values in the right way in Python 3?

推荐答案

元组解包的移除在 PEP 3113.基本上,你不能在 Python 3 中做到这一点.在标题下 过渡计划,您会看到建议的"这样做的方式是您的最终代码块:

The removal of tuple unpacking is discussed in PEP 3113. Basically, you can't do this in Python 3. Under the headline Transition plan, you see that the "suggested" way of doing this is as your final code block:

lambda x_y: x_y[0] + x_y[1]

这篇关于lambda 参数解包错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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