Python lambda 不接受元组参数 [英] Python lambda does not accept tuple argument
问题描述
我在 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屋!