如何在python中对嵌套的听写列表进行排序?

如何在python中对嵌套的听写列表进行排序?,python,Python,您可以考虑以下列表 [{'mesa': {'url': 'https://anongit.freedesktop.org/git/mesa/mesa.git', 'commit': 'a6e212440278df2bb0766a5cf745935d94809144', 'location': 2}}, {'macros': {'url': 'https://anongit.freedesktop.org/git/xorg/util/macros.git', 'commit': '39f07f7d

您可以考虑以下列表

[{'mesa': {'url': 'https://anongit.freedesktop.org/git/mesa/mesa.git', 'commit': 'a6e212440278df2bb0766a5cf745935d94809144', 'location': 2}}, {'macros': {'url': 'https://anongit.freedesktop.org/git/xorg/util/macros.git', 'commit': '39f07f7db58ebbf3dcb64a2bf9098ed5cf3d1223', 'location': 7}}, {'drm': {'url': 'https://anongit.freedesktop.org/git/mesa/drm.git', 'commit': '19c4cfc54918d361f2535aec16650e9f0be667cd', 'location': 1}}]
我想按键“位置”对字典列表进行排序

谢谢

使用该方法,传入适当的key=参数。例如:

l.sort(key=lambda x: list(x.values())[0]['location'])
完整程序:

from pprint import pprint
l=[{'mesa': {'url': 'https://anongit.freedesktop.org/git/mesa/mesa.git', 'commit': 'a6e212440278df2bb0766a5cf745935d94809144', 'location': 2}}, {'macros': {'url': 'https://anongit.freedesktop.org/git/xorg/util/macros.git', 'commit': '39f07f7db58ebbf3dcb64a2bf9098ed5cf3d1223', 'location': 7}}, {'drm': {'url': 'https://anongit.freedesktop.org/git/mesa/drm.git', 'commit': '19c4cfc54918d361f2535aec16650e9f0be667cd', 'location': 1}}]

l.sort(key=lambda x: list(x.values())[0]['location'])
pprint(l)
sort和sorted都有一个关键参数。如果你在谷歌上搜索,你应该能够在一分钟左右回答你自己的问题。可能是重复的