python按年龄降序排列输出和按姓名降序排列输出
时间: 2023-04-03 20:01:40 浏览: 204
可以使用Python中的sorted函数进行排序,按照年龄降序排列可以使用lambda表达式指定按照年龄排序,按照姓名降序排列可以指定按照姓名排序。示例代码如下:
按照年龄降序排列:
```
students = [{'name': 'Tom', 'age': 20}, {'name': 'Jerry', 'age': 18}, {'name': 'Alice', 'age': 22}]
sorted_students = sorted(students, key=lambda x: x['age'], reverse=True)
print(sorted_students)
```
输出结果为:
```
[{'name': 'Alice', 'age': 22}, {'name': 'Tom', 'age': 20}, {'name': 'Jerry', 'age': 18}]
```
按照姓名降序排列:
```
students = [{'name': 'Tom', 'age': 20}, {'name': 'Jerry', 'age': 18}, {'name': 'Alice', 'age': 22}]
sorted_students = sorted(students, key=lambda x: x['name'], reverse=True)
print(sorted_students)
```
输出结果为:
```
[{'name': 'Tom', 'age': 20}, {'name': 'Jerry', 'age': 18}, {'name': 'Alice', 'age': 22}]
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)