python - 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
解决方案
在 Python 2.7 中,函数的签名sorted
是sorted(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 元组是没有意义的。
推荐阅读
- sympy - 使用涉及 SymPy 中变量之间关系的假设简化表达式
- c# - 在循环中创建元素并定位它们,从左下角到右上角
- angular - 角度形式:如何确保选择多选按钮组中的至少一项
- r - 对于每一行,将字符分配给该行中的第一个最大值
- node.js - Express 端点不反映更改。奇怪的行为
- html - 如何在父级伪类之前修复
- postgresql - Postgresql 9.6 级联流复制问题:物理复制槽未从主服务器同步到从服务器
- powerbi - 将 DAX 创建的表从 DAXStudio 复制到 Power BI
- amazon-web-services - 是否有完整的 AWS 资源操作列表?
- string - 在 Powershell 中传递带有空格的参数列表