python - Using itemgetter instead of lambda
问题描述
Is it possible to put the following sort into using the itemgetter
operator?
res = sorted(res, key = lambda x: (x['operation'], x['path']))
Previously I had res.sort(key=itemgetter("path"))
, but I was having trouble figuring out how to sort in-place with multiple sorts.
解决方案
你可以这样做:
from operator import itemgetter
res = [{"operation": 1, "path": 2}, {"operation": 1, "path": 1}]
res = sorted(res, key=itemgetter("operation", "path"))
print(res)
输出
[{'operation': 1, 'path': 1}, {'operation': 1, 'path': 2}]
推荐阅读
- mysql - 计算多个时间戳之间的差异
- node.js - 以快递方式同时发送错误状态(res.status)和消息(res.json)
- angular - 编辑模式下的角负载选择下拉值
- javascript - 在 react 之外修改 reactjs 表单输入值
- github - 深度学习聊天机器人特定索引错误列表索引超出范围
- sap-iq - 如何在 Sybase 中获取与给定字符串匹配的所有列名?
- javascript - Javascript 数组为第一个结果返回“空”
- c# - 一次创业下的不同种子
- git - 如何将隐藏文件合并到当前分支
- python - 为什么 a=[0] 的 list(x for x in a) 比 a=[] 快?