主要内容 #
- 字典元素排序
- 列表字典排序
1. 字典元素排序 #
字典本身是无序的,想要排序的话,就必须先转化成可排序的数据结构,常见的是列表。
对列表的排序可通过python的内置函数sorted()执行,语法如下:
list1 = sorted(iterable, key=None, reverse=False)
参数说明:
iterable:可迭代对象
key:用于比较的元素
reverse:排序规则,reverse=True(降序排序),reverse=False (升序排序)
功能:
返回重新排序的列表,赋值给list1
Chinese = {"Xiao": 85 , "Li": 96, "Da": 80}
#通过字典内置函数items()返回可迭代对象
#对字典的‘键’进行升序排序
list1 = sorted(Chinese.items(), key=lambda x:x[0], reverse=False)
print(list1)
#对字典的‘值’进行降序排序
list2 = sorted(Chinese.items(), key=lambda x:x[1], reverse=True)
print(list2)
2. 列表字典排序 #
字典的value可以是列表,也可以是字典
列表的元素可以是列表,也可以是字典
当列表的元素是字典时,称之为列表字典
比如:
student=[
{"name": "小明", "birth": "2005/06", "code": 101, "语文": 85},
{"name": "莉莉", "birth": "2005/08", "code": 102 , "语文": 96},
{"name": "大雄", "birth": "2006/02", "code": 103 , "语文": 80}
]
通过列表的内置函数sort()对列表字典进行排序:
student=[
{"name": "小明", "birth": "2005/06", "code": 101, "语文": 85},
{"name": "莉莉", "birth": "2005/08", "code": 102 , "语文": 96},
{"name": "大雄", "birth": "2006/02", "code": 103 , "语文": 80}
]
#将语文成绩按升序排序
student.sort(key=lambda x:x.get("语文"))
print(student)
#将语文成绩按降序排序
student.sort(key=lambda x:-x.get("语文"))
print(student)