英文:
How to Implement Multi-Level Sorting of a List of Dictionaries in Python?
问题
我正在使用Python中的一组字典列表,表示一组数据记录。数据结构如下:
data = [
{'Name': 'Tom', 'Age': 25, 'Score': 85},
{'Name': 'Alex', 'Age': 30, 'Score': 80},
{'Name': 'Tom', 'Age': 20, 'Score': 90},
{'Name': 'Alex', 'Age': 25, 'Score': 95},
{'Name': 'Tom', 'Age': 25, 'Score': 80},
{'Name': 'Alex', 'Age': 30, 'Score': 85}
]
列表中的每个字典表示一个单独的记录,具有'Name'、'Age'和'Score'作为字段。我的目标是根据多个字段对这个字典列表进行排序。我想首先按字母顺序对'Name'字段进行排序,然后按升序对'Age'字段进行排序,最后按降序对'Score'字段进行排序。
我一直在尝试使用Python中的sorted()函数,但我无法弄清楚如何同时按多个字段排序,特别是如何按不同方向对不同字段进行排序。
我想知道在Python中实现这种多级排序的最有效方法。任何建议将不胜感激。
英文:
I am working with a list of dictionaries in Python that represents a set of data records. The data structure looks like this:
data = [
{'Name': 'Tom', 'Age': 25, 'Score': 85},
{'Name': 'Alex', 'Age': 30, 'Score': 80},
{'Name': 'Tom', 'Age': 20, 'Score': 90},
{'Name': 'Alex', 'Age': 25, 'Score': 95},
{'Name': 'Tom', 'Age': 25, 'Score': 80},
{'Name': 'Alex', 'Age': 30, 'Score': 85}
]
Each dictionary in the list represents a single record with 'Name', 'Age', and 'Score' as fields. My goal is to sort this list of dictionaries according to multiple fields. I want to sort it first by the 'Name' field in alphabetical order, then by the 'Age' field in ascending numerical order, and finally by the 'Score' field in descending numerical order.
I have been trying to use the sorted() function in Python, but I can't figure out how to sort by multiple fields at once, and especially not how to sort by different fields in different directions.
I would like to know the most efficient way to achieve this multi-level sort in Python. Any suggestions would be greatly appreciated.
答案1
得分: 3
你可以在 sorted()
或 .sort()
中使用 key=
参数。key 参数将返回一个包含 3 个元素的元组,其中分数被取反(以便按降序排列):
data.sort(key=lambda d: (d["Name"], d["Age"], -d["Score"]))
print(data)
输出结果:
[
{"Name": "Alex", "Age": 30, "Score": 85},
{"Name": "Alex", "Age": 30, "Score": 80},
{"Name": "Alex", "Age": 25, "Score": 95},
{"Name": "Tom", "Age": 25, "Score": 85},
{"Name": "Tom", "Age": 25, "Score": 80},
{"Name": "Tom", "Age": 20, "Score": 90}
]
英文:
You can use key=
parameter in sorted()
or .sort()
. The key parameter will return 3-item tuple, where the score is negated (to have it in descending order):
data.sort(key=lambda d: (d["Name"], d["Age"], -d["Score"]))
print(data)
Prints:
[
{"Name": "Alex", "Age": 25, "Score": 95},
{"Name": "Alex", "Age": 30, "Score": 85},
{"Name": "Alex", "Age": 30, "Score": 80},
{"Name": "Tom", "Age": 20, "Score": 90},
{"Name": "Tom", "Age": 25, "Score": 85},
{"Name": "Tom", "Age": 25, "Score": 80},
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论