sorted()函数排序的灵活运用---面试

知识点:

 


题目一:列表嵌套字典的排序,分别根据年龄和姓名排序

foo = [{"name":"zs","age":19},{"name":"ll","age":54},
{"name":"wa","age":17},{"name":"df","age":23}]

 1 foo = [{"name": "zs", "age": 19}, {"name": "ll", "age": 54},
 2 
 3         {"name": "wa", "age": 17}, {"name": "df", "age": 23}]
 4 
 5 
 6 a = sorted(foo, key=lambda x: x['age'], reverse=True)
 7 print('按照年龄倒序排列:', a)
 8 
 9 a = sorted(foo, key=lambda x: x['name'])
10 print('按照姓名排序:', a)

运行结果如下:

 

题目二:列表嵌套元组,分别按字母和数字排序
foo = [("ab", 20), ("ur", 30), ("wa", 19), ('zf', 23)]
1 foo = [("ab", 20), ("ur", 30), ("wa", 19), ('zf', 23)]
2 a = sorted(foo, key=lambda x: x[0], reverse=True)  # reverse=True是降序,reverse=False是升序(默认)
3 print('按照字母排序的结果是:', a)
4 a = sorted(foo, key=lambda x: x[1])
5 print('按照数字排序的结果是:', a

运行结果如下:

 

题目三:列表嵌套列表排序,年龄数字相同怎么办?
foo = [("ab", 20), ("ur", 30), ("wa", 19), ('zf', 23), ('ha', 23), ('nb', 23)]

 

1 foo = [("ab", 20), ("ur", 30), ("wa", 19), ('zf', 23), ('ha', 23), ('nb', 23)]
2 a = sorted(foo, key=lambda x: (x[1], x[0]))  # 年龄相同怎么办?lambda表达式的key值添加参数,按字母排序
3 print('按年龄排序,年龄相同的按照姓名排序:', a)

运行结果是:

 

 题目四:根据字符串长度排序

s = ['ab', 'uuu', 'w', 'iudsc', 'sdgfkjsgfasu', 'qq', 'uytg']

1 s = ['ab', 'uuu', 'w', 'iudsc', 'sdgfkjsgfasu', 'qq', 'uytg']
2 # 使用sorted方法.sorted函数有返回值,不改变s本身的值
3 s_new = sorted(s, key=lambda x: len(x))
4 print(s_new, s)
5 
6 # 使用sort方法。sort函数没有返回值,是修改s本身。
7 s.sort(key=len)
8 print(s)

运行结果是:

 

 

 
posted @ 2020-09-07 10:10  anna1210  阅读(259)  评论(0编辑  收藏  举报