python排序 sort 和 sorted
2020-01-15 11:09
1821 查看
注意:
1、sorted(iterable[, cmp[, key[, reverse]]]) 作用于任何可迭代对象,返回列表,不改变原对象;
2、s.sort([cmp[, key[, reverse]]]) 只作用与列表,返回 None;
一、字典
from operator import itemgetter # 字典(比较item中位置1中的元素,如果位置1相同在比较位置0中的元素) phonebook = {'Linda': '7750', 'Bob': '9345', 'Carol': '5834', 'Abc': '5834'} result = sorted(phonebook.items(), key=itemgetter(1, 0)) result = sorted(phonebook.items(), key=lambda item:(item[1], item[0]))
二、列表中套字典
persons = [{'name':'Join', 'age':36}, {'name':'Hoin', 'age':26}, {'name': 'Boin', 'age': 28}, {'name': 'Boin', 'age': 26}, {'name': 'Zoin', 'age': 15}, {'name': 'moin', 'age': 20},] # 按照名字排序,如果名字一样,按照年龄,默认,升序 # 方法1:sort方法,直接改变persons对象 persons.sort(key=lambda x:(x['name'], x['age'])) # 方法2 persons.sort(key=itemgetter('name', 'age')) # 方法3 sorted方法,不改变persons对象,返回值就是已经排序好的对象 print(sorted(persons, key=lambda x:(x['name'], x['age']))) print(sorted(persons, key=itemgetter('name', 'age')))
三、多维列表
gameresult = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']] result = sorted(gameresult, key=itemgetter(1, 2)) result = sorted(gameresult, key=lambda x:(x[2], x[1])) print(result)
四、字典中混合列表
mydict = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]} result = sorted(mydict.items(), key=itemgetter(1))# 无法按照列表中的非0位置的值排序 result = sorted(mydict.items(), key=lambda item:(item[1][1], item[0]))#能详细按照各个值排序
五、字典中混合字典
data = {'a': {'Country': 'China'}, 'c': {'Country': 'USA'}, 'b': {'Country': 'Russia'}, 'd': {'Country': 'Canada'}} result = sorted(data.items(), key=lambda item:item[1]['Country'])# 此处子字典中要有相同的 key
六、分组排序
mydata = ['GetInfo.h', 'GetInfo.m', 'NetTool.h', 'Toolbar.h', 'Toolbar.m', 'Store.h', 'AES.h', 'AES.m'] mydata.sort() from itertools import groupby # 分组(必须先排序) result = groupby(mydata, key=lambda item:item.split('.')[0]) result = [list(value) for _, value in result] print(result) # [['AES.h', 'AES.m'], ['GetInfo.h', 'GetInfo.m'], ['NetTool.h'], ['Store.h'], ['Toolbar.h', 'Toolbar.m']]
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- 【Python】 sort、sorted高级排序技巧
- python list排序sort和sorted的区别
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- Python中排序常用到的sort 、sorted和argsort函数
- Python 列表排序方法reverse、sort、sorted详解
- python sort、sorted高级排序技巧
- python sort、sorted高级排序技巧
- Python中排序常用到的sort 、sorted和argsort函数
- Python 列表排序方法reverse、sort、sorted操作方法
- python容器排序sort()和内建函数sorted()的区别
- leetcode—217. Contains Duplicate 查找双数,python排序sort、sorted,for遍历的范围
- python sort、sorted高级排序技巧
- Python 排序---sort与sorted学习
- python 中的排序方法:sorted() 和 sort()
- Python中排序常用到的sort 、sorted和argsort函数
- 【python学习笔记】Python中排序sorted()和list.sort()
- Python中的排序函数argsort,sort,sorted
- Python的排序函数Sort,Sorted
- Python之排序函数sort() 和 sorted()