运行有问题或需要源码请点赞关注收藏后评论区留言且私信~~~
一、自定义排序规则
自定义rulesort函数规定排序规则 并且按照分数降序排列后效果如下
def rulesort(elem): # 定义排序规则
print("自定义排序规则")
list_dict = [{"name":"小黑子","python":99,"c":89},
{"name":"小鸡子","python":100,"c":80},
{"name":"ikun","python":95,"c":97},
{"name":"背带裤","python":91,"c":96}]
print("对列表排序前:")
for d in list_dict:
print(d)
list_dict.sort(key = rulesort ,reverse = True) # 降序排列
print("对列表排序后:")
print(d)
二、使用lambda表达式
使用lambda表达式按照考试分数进行降序排列后效果如下
代码如下
print("lambda表达式")
list_dict = [{"name":"小黑子","python":99,"c":89},
{"name":"小鸡子","python":100,"c":80},
{"name":"ikun","python":95,"c":97},
{"name":"背带裤","python":91,"c":96}]
print("对列表排序前:")
for d in list_dict:
print(d)
list_dict.sort(key = lambda x :x['python'] ,reverse = True) # 降序排列
print("对列表排序后:")
for d in list_dict:
print(d)