在Python中,可以使用sorted()
函数和operator.itemgetter()
函数来按照两个字段进行排序。以下是一个示例代码:
import operator
# 定义一个列表
data = [
{'name': 'John', 'age': 25, 'score': 80},
{'name': 'Alice', 'age': 20, 'score': 90},
{'name': 'Bob', 'age': 30, 'score': 70},
{'name': 'David', 'age': 25, 'score': 85}
]
# 按照age字段和score字段进行排序
sorted_data = sorted(data, key=operator.itemgetter('age', 'score'))
# 打印排序后的结果
for d in sorted_data:
print(d)
输出结果:
{'name': 'Alice', 'age': 20, 'score': 90}
{'name': 'John', 'age': 25, 'score': 80}
{'name': 'David', 'age': 25, 'score': 85}
{'name': 'Bob', 'age': 30, 'score': 70}
在上面的代码中,我们使用operator.itemgetter()
函数来指定按照哪些字段进行排序。operator.itemgetter('age', 'score')
表示先按照age字段进行排序,如果age相同,则按照score字段进行排序。然后,我们使用sorted()
函数来对data列表进行排序,并将排序结果赋值给sorted_data。最后,我们遍历sorted_data列表,并打印排序后的结果。