列表的排序
1、升序、降序采用sorted函数,返回排序后的结果
list1=[7,2,55,312,32]
list2asc=sorted(list1)
print("升序排序结果:")
print(list2asc)
list3desc=sorted(list1,reverse=True)
print("降序排序结果:")
print(list3desc)
2、逆序采用reversed函数,返回逆序的结果
list1=[7,2,55,312,32]
list4rev=list(reversed(list1))
print("逆序排序结果:")
print(list4rev)
3、列表的复杂排序
list5=[["老刘",40],["老张",60],["老李",47]]
list6asc=sorted(list5,key=lambda list5:list5[1])
print(list6asc)
list7desc=sorted(list5,key=lambda list5:list5[1],reverse=True)
print(list7desc)
字典的排序
1、采用魔术属性排序,对字典的键进行排序,按照键来进行升序或者降序
dic1={"d2":25,"d1":76,"d3":115}
dic2asc=sorted(dic1,key=dic1.__getitem__)
for i in dic2asc:
print(i,dic1[i])
dic1={"d2":25,"d1":76,"d3":115}
dic3desc=sorted(dic1,key=dic1.__getitem__,reverse=True)
for i in dic3desc:
print(i,dic1[i])
2、items方法,结合lambda表达式排序,默认输出的是列表的结果,可用dict函数转化为字典
dic1={"d2":25,"d1":76,"d3":115}
dic4asc=dict(sorted(dic1.items(),key=lambda dic1:dic1[1]))
print(dic4asc)
dic1={"d2":25,"d1":76,"d3":115}
dic5desc=dict(sorted(dic1.items(),key=lambda dic1:dic1[1],reverse=True))
print(dic5desc)