在dicts列表中,查找公共dict字段的min()值
-
24-10-2019 - |
题
我有这样的字典列表:
[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
我想找到最低()和max()价格。现在,我可以使用带有lambda表达式的键(如另一篇文章中找到)轻松地对其进行排序,因此,如果没有其他方法,我不会卡住。但是,从我所看到的,Python几乎总是有一种直接的方式,因此这是我学习更多的机会。
解决方案
有几个选择。这是一个直接的:
seq = [x['the_key'] for x in dict_list]
min(seq)
max(seq)
编辑
如果您只想一次迭代列表,则可以尝试(假设值可以表示为 int
S):
import sys
lo,hi = sys.maxint,-sys.maxint-1
for x in (item['the_key'] for item in dict_list):
lo,hi = min(x,lo),max(x,hi)
其他提示
lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
maxPricedItem = max(lst, key=lambda x:x['price'])
minPricedItem = min(lst, key=lambda x:x['price'])
这不仅告诉您最高价格是多少,还告诉您哪个最昂贵的项目。
我认为最直接(和最蓬松的)表达方式将是:
min_price = min(item['price'] for item in items)
这避免了对列表进行排序的开销 - 以及通过使用生成器表达式而不是列表理解的开销实际上也避免了创建任何列表。高效,直接,可读... Pythonic!
一个答案是将您的命令映射到发电机表达式中感兴趣的价值,然后应用内置 min
和 max
.
myMax = max(d['price'] for d in myList)
myMin = min(d['price'] for d in myList)
也可以使用以下方式:
from operator import itemgetter
lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
max(map(itemgetter('price'), lst))
不隶属于 StackOverflow