1. 问题:
怎么从数值列表中获取最大或最小几个元素?
怎么从字典元素列表中,获取字典中某个值最大或最小的几个字典元素?
2. 解决方法:
使用heapq模块中的nlargest、nsmallest。
- 示例:
import heapq
test_list = [1, 3, 6, 2, 9, 10, 4]
test_dict = [
{"name": "BMW", "price": 20000},
{"name": "Benz", "price": 50000},
{"name": "Audi", "price": 3000},
{"name": "BYD", "price": 1000},
{"name": "丰田", "price": 9000},
{"name": "保时捷", "price": 600000},
]
# 获取列表中最大的3个元素
large_3 = heapq.nlargest(3, test_list)
print(f"列表中最大的3个元素: {large_3}")
# 获取列表中最小的2个元素
least_2 = heapq.nsmallest(2, test_list)
print(f"列表中最小的2个元素: {least_2}")
# 列表中根据字典某个键,获取最大2个元素
dict_large_2 = heapq.nlargest(2, test_dict, key=lambda s: s["price"])
print(f"列表中字典元素价格最大的2个元素: {dict_large_2}")
# 列表中根据字典某个键,获取最小3个元素
dict_least_3 = heapq.nsmallest(3, test_dict, key=lambda s: s["price"])
print(f"列表中字典元素价格最小的3个元素: {dict_least_3}")
- 示例结果: