按宠物年龄的大小进行升序排序,如果年龄相同则按照体重从小到大的顺序进行排序。
时间: 2023-06-13 15:08:17 浏览: 49
可以使用Python中的sorted函数,结合lambda表达式来实现宠物年龄和体重的排序。代码如下:
```python
pets = [
{'name': 'Tom', 'age': 2, 'weight': 5},
{'name': 'Jerry', 'age': 3, 'weight': 3},
{'name': 'Spike', 'age': 2, 'weight': 7},
{'name': 'Tweety', 'age': 1, 'weight': 2},
{'name': 'Sylvester', 'age': 1, 'weight': 4}
]
sorted_pets = sorted(pets, key=lambda pet: (pet['age'], pet['weight']))
print(sorted_pets)
```
输出结果为:
```
[{'name': 'Tweety', 'age': 1, 'weight': 2}, {'name': 'Sylvester', 'age': 1, 'weight': 4}, {'name': 'Tom', 'age': 2, 'weight': 5}, {'name': 'Spike', 'age': 2, 'weight': 7}, {'name': 'Jerry', 'age': 3, 'weight': 3}]
```
可以看到,宠物列表按照年龄升序排序,如果年龄相同则按照体重从小到大排序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)