首页 > 解决方案 > sorted not taking lambda returning tuple as key argument

问题描述

I am trying to sort an array by several criteria. Python's sorted function can take a tuple as a key for this purpose. It can also take a lambda argument as key. I've tried a lambda returning a tuple as key and got TypeError: <lambda>() takes exactly 1 argument (2 given) and a tuple of lambdas and got TypeError: 'tuple' object is not callable. I am using Python 2.7.13 on windows.

Does anybody know why I get this error and how to fix it?

Example:

In [1]: message = {'tcu':1,'timestamps':{'device':23432}}

In [2]: message_array = [message, message]

In [3]: key = lambda message: (message['tcu'], message['timestamps']['device'])

In [4]: sorted(message_array,key)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-45bd2b89f64b> in <module>()
----> 1 sorted(message_array,key)

TypeError: <lambda>() takes exactly 1 argument (2 given)

In [5]: key = (lambda message: message['tcu'], lambda message: message['timestamps']['device'])

In [6]: sorted(message_array,key)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-45bd2b89f64b> in <module>()
----> 1 sorted(message_array,key)

TypeError: 'tuple' object is not callable

标签: pythonpython-2.7sorting

解决方案


在 Python 2.7 中,函数的签名sortedsorted(iterable[, cmp[, key[, reverse]]]). 您将一个键函数作为第二个参数传递,而实际上它是第三个参数。要始终确保将正确的东西传递给函数,请使用命名参数。

message = {'tcu':1,'timestamps':{'device':23432}}
message_array = [message, message]
key = lambda message: (message['tcu'], message['timestamps']['device'])
sorted(message_array, key=key)

由于key应该是一个接受一个参数的函数,因此传入一个 lambda 元组是没有意义的。


推荐阅读