如何在字典列表中查找公共键的最小/最大值?
我有一个像这样的字典列表:
[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
我想找到 min()
和 max()
价格。现在,我可以使用带有 lambda 表达式的键(如另一篇 Stack Overflow 帖子中所示)轻松地对此进行排序,因此如果没有其他方法,我就不会陷入困境。然而,据我所知,Python 中几乎总是有直接的方法,所以这对我来说是一个学习更多知识的机会。
I have a list of dictionaries 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 Stack Overflow post), 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这不仅告诉您最高价格是多少,还告诉您哪件商品最贵。
This tells you not just what the max price is but also which item is most expensive.
有几种选择。这是一个简单的方法:
[编辑]
如果您只想遍历列表一次,您可以尝试此操作(假设值可以表示为 int ):
There are several options. Here is a straight-forward one:
[Edit]
If you only wanted to iterate through the list once, you could try this (assuming the values could be represented as
int
s):我认为最直接(也是最Pythonic)的表达式类似于:
这避免了对列表进行排序的开销——并且通过使用生成器表达式而不是列表理解——实际上也避免了创建任何列表。高效、直接、可读……Pythonic!
I think the most direct (and most Pythonic) expression would be something like:
This avoids the overhead of sorting the list -- and, by using a generator expression, instead of a list comprehension -- actually avoids creating any lists, as well. Efficient, direct, readable... Pythonic!
一种答案是将您的字典映射到生成器表达式中感兴趣的值,然后应用内置的
min
和max
。One answer would be mapping your dicts to the value of interest inside a generator expression, and then applying the built-ins
min
andmax
.也可以使用这个:
can also use this:
并添加到这个伟大的页面:通用便捷功能中的最佳答案:
>>> {'score': 0.995, 'label': 'buildings'}
And to add to this great page: the top answer in a generic convenient function:
>>> {'score': 0.995, 'label': 'buildings'}