python中有查询字典的简写吗?
这是我想要执行的查询类型,用伪代码编写:
select blob from blobs where blob['color'] == 'red' having maximum(blob['size'])
显然,我可以在 python 中这样写:
redBlobs = [];
for blob in blobs:
if blob['color'] == 'red':
redBlobs.append('blob')
largestBlob = None
for redBlob in redBlobs:
if largestBlob == None or redBlob['size'] > largestBlob['size']:
largestBlob = redBlob
return largestBlob
但我怀疑有一种更简洁的方法可以做到这一点。我是Python新手,所以我仍然非常迫切地学习它。
编辑:
这是我在查看 SO 上的其他一些问题后提出的解决方案:
max([blob for blob in blobs if blob['color'] == 'red'], key = lambda b: b['size'])
大概有更好的方法。
Here's the type of query I want to execute, written in pseudocode:
select blob from blobs where blob['color'] == 'red' having maximum(blob['size'])
Obviously, I could write that like this in python:
redBlobs = [];
for blob in blobs:
if blob['color'] == 'red':
redBlobs.append('blob')
largestBlob = None
for redBlob in redBlobs:
if largestBlob == None or redBlob['size'] > largestBlob['size']:
largestBlob = redBlob
return largestBlob
But I suspect there's a cleaner way of doing it. I'm new to python, so I'm still aproaching it very imperatively.
EDIT:
Here's a solution I came up with after looking at some other questions on SO:
max([blob for blob in blobs if blob['color'] == 'red'], key = lambda b: b['size'])
Presumably, there are better ways.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下给出最大的斑点
编辑:当没有红色斑点时捕获异常
The folowing give the largest blob
EDIT: catch exception when there is no red blob
这将完成这项工作:
This will do the job:
PiotrLegnica 的答案将返回最大斑点的大小,而不是最大斑点本身。要获得最大的 blob,请使用 max 的可选“key”参数:
PiotrLegnica's answer will return the size of the largest blob, not the largest blob itself. To get the largest blob, use the optional "key" argument to max:
如果我是你,我会使用排序,使用大小作为键,并使用生成器表达式进行筛选,获取该列表的第一个元素:
If I were you I would use sorted using the size as key with a generator expression for filetering, getting the first element of that list: