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

查看:188
本文介绍了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天全站免登陆