首页 > 解决方案 > 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.

标签: pythonpython-3.x

解决方案


你可以这样做:

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}]

推荐阅读