在列表列表中,找到一个常见的Dict字段的min()值 [英] In List of Dicts, find min() value of a common Dict field

查看:182
本文介绍了在列表列表中,找到一个常见的Dict字段的min()值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的列表:

  [{'price':99,'barcode':'2342355 '},{'price':88,'barcode':'2345566'}] 

找到min()和max()价格。现在,我可以使用一个带有lambda表达式的键(如另一个SO文章)轻松地排序,所以如果没有其他方式我没有被卡住。然而,从我所看到的,Python几乎总是有直接的方式,所以这是一个让我学习更多的机会。



TIA, p>

Hank Fay

解决方案

有几个选项。这是一个简单的例子:

  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 dict in dict_list):
lo,hi = min(x,lo),max(x,hi)
/ pre>

I have a list of dicts like so:

[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]

I want to find the min() and max() prices. Now, I can sort this easily enough using a key with a lambda expression (as found in another SO article), so if there is no other way I'm not stuck. However, from what I've seen there is almost always a direct way in Python, so this is an opportunity for me to learn a bit more.

TIA,

Hank Fay

解决方案

There are several options. Here is a straight-forward one:

seq = [x['the_key'] for x in dict_list]
min(seq)
max(seq)

[Edit]

If you only wanted to iterate through the list once, you could try this (assuming the values could be represented as ints):

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)

这篇关于在列表列表中,找到一个常见的Dict字段的min()值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆