我有一个像这样的字典列表:
[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
我想找到最小值(min()
)和最大值(max()
)的价格。现在,我可以使用lambda表达式中的键轻松地进行排序(就像在另一个Stack Overflow帖子中发现的那样),所以如果没有其他方法,我不会卡壳。但是,从我所看到的情况来看,Python几乎总是有一种直接的方法,因此这是一个让我学到更多的机会。
我有一个像这样的字典列表:
[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
我想找到最小值(min()
)和最大值(max()
)的价格。现在,我可以使用lambda表达式中的键轻松地进行排序(就像在另一个Stack Overflow帖子中发现的那样),所以如果没有其他方法,我不会卡壳。但是,从我所看到的情况来看,Python几乎总是有一种直接的方法,因此这是一个让我学到更多的机会。
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'])
这不仅告诉您最高价格是多少,还告诉您哪个物品最贵。
有几种选择。这里是一个简单直接的选择:
seq = [x['the_key'] for x in dict_list]
min(seq)
max(seq)
[编辑]
如果您只想遍历列表一次,您可以尝试这样做(假设值可以表示为int
):
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)
seq
,且列表很大,则这可能效率低下,因为必须分配整个列表的内存才能找到最大值。 - Charles L.AttributeError: module 'sys' has no attribute 'maxint'
。 - Suncatchersys.maxint
е·Із»Ҹиў«жӣҙж”№дёәsys.maxsize
гҖӮиҜ·жіЁж„ҸпјҢзҝ»иҜ‘з»“жһңдёҚеҢ…жӢ¬и§ЈйҮҠжҲ–е…¶д»–йўқеӨ–дҝЎжҒҜгҖӮ - Daniel Lavedonio de Lima我认为最直接(也是最符合Python风格)的表达方式可能是:
min_price = min(item['price'] for item in items)
这种方法避免了对列表的排序开销 - 而且,通过使用生成器表达式而不是列表推导式 - 实际上避免了创建任何列表。高效、直接、易读……符合 Python 风格!
其中一种解决方法是在生成器表达式中将你的字典映射为感兴趣的值,然后应用内置函数min
和max
。
myMax = max(d['price'] for d in myList)
myMin = min(d['price'] for d in myList)
[
和]
括起来,实际上会生成一个Python列表作为中间步骤。 - dcrostafrom operator import itemgetter
lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
max(map(itemgetter('price'), lst))
def takeMaxFromDictList(listOfDicts: list, keyToLookAt: str) -> dict:
return max( listOfDicts, key=lambda x: x[keyToLookAt] )
# -------------------------------------------------------------------
examplelist = [{'score': 0.995, 'label': 'buildings'},
{'score': 0.002, 'label': 'mountain'},
{'score': 0.001, 'label': 'forest'}]
print ( takeMaxFromDictList(examplelist, 'score') )