使用itemgetter代替lambd

2024-04-19 22:48:14 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使用itemgetter运算符进行以下排序?你知道吗

res = sorted(res, key = lambda x: (x['operation'], x['path']))

以前我有res.sort(key=itemgetter("path")),但是我很难弄清楚如何使用多个排序进行适当的排序。你知道吗


Tags: pathlambdakey排序运算符ressortoperation
1条回答
网友
1楼 · 发布于 2024-04-19 22:48:14

你可以做:

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

相关问题 更多 >