Python lambda 不接受元组参数 [英] Python lambda does not accept tuple argument

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

问题描述

我在 Linux 和 Windows 的两台 PC 上运行带有 PyDev v2.6 插件的 Eclipse SDK v3.6.

I am running Eclipse SDK v3.6 with PyDev v2.6 plugin on two PC, with Linux and Windows.

我想传递一个元组作为参数,例如:

I would like to pass a tuple as an argument, like:

foo = lambda (x,y): (y,x)
print (foo((1,2)))

这适用于 Linux 并给出正确的结果:

This works on Linux and gives the correct result:

> (2,1)

在 Windows 上出现错误:

On Windows it rises an error:

foo = lambda (x,y): (y,x)
             ^
SyntaxError: invalid syntax

如何解决问题?

推荐答案

您可能在 Windows 上运行 Python 3.x,在 Linux 上运行 Python 2.x.Python 3 中删除了解包元组参数的功能:请参阅 PEP 3113.

You are probably running Python 3.x on Windows, and Python 2.x on Linux. The ability to unpack tuple parameters was removed in Python 3: See PEP 3113.

您可以改为手动解包元组,这适用于 Python 2.x 和 3.x:

You can manually unpack the tuple instead, which would work on both Python 2.x and 3.x:

foo = lambda xy: (xy[1],xy[0])

或者:

def foo(xy):
    x,y = xy
    return (y,x)

这篇关于Python lambda 不接受元组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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