用lambda()实现对列表,字典的排序
1、对list排序foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4],使用lambda函数从小到大排序
foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4]
k=sorted(foo,key=lambda x:x)
2、使用lambda函数对list排序foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4],输出结果为
[0,2,4,8,8,9,-2,-4,-4,-5,-20],正数从小到大,负数从大到小
foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4]
k=sorted(foo,key=lambda x:(x<0,abs(x)))
3、列表嵌套字典的排序,分别根据年龄和姓名排序
foo = [{"name":"zs","age":19},
{"name":"ll","age":54},
{"name":"wa","age":17},
{"name":"df","age":23}]
k=sorted(foo,key=lambda x:x["name"])
k=sorted(foo,key=lambda x:x["age"])
4、列表嵌套元组,分别按字母和数字排序
foo = [("zs",19),
("ll",54),
("wa",17),
("df",23)]
k=sorted(foo,key=lambda x:x[0])
k=sorted(foo,key=lambda x:x[1])
5、列表嵌套列表排序,年龄数字相同怎么办?
foo = [["zs",19],["ll",54],["wa",17],["sd",17],["df",73],["df",45]]
k=sorted(foo,key=lambda x:(x[1],x[0]))
6、根据键对字典排序(方法一,zip函数)
foo={"name":"zs","age":19,'city':"shanghai","sex":"F"}
k=zip(foo.keys(),foo.values())
kk=[x for x in k]
ss=sorted(kk,key=lambda x:x[0])
new_dict={}
for i in ss:
new_dict.setdefault(i[0],i[1])
print(new_dict)
7、根据键对字典排序(方法二,不用zip)
foo={"name":"zs","age":19,'city':"shanghai","sex":"F"}
k=sorted(foo.keys())
new_dict={}
for i in k:
new_dict.setdefault(i,foo[i])