开发者

Is there a shorthand for querying a dictionary in python?

开发者 https://www.devze.com 2023-02-21 17:03 出处:网络
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\'])

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.


The folowing give the largest blob

EDIT: catch exception when there is no red blob

import operator
try:
    largestBlob = max((blob for blob in blobs if blob['color'] == 'red'),key=operator.itemgetter('size'))
except ValueError:
    largestBlob = None


This will do the job:

redBlobs = filter(lambda b: b['color'] == 'red', blobs)
largestBlob = max(redBlobs, key=lambda b: b['size'])


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:

largestBlob = max((blob for blob in blobs if blob['color'] == 'red'), key=operator.itemgetter('size'))


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:

largestBlob = sorted((blob for blob in blobs if blob['color'] == 'red'), key=lambda x: -x['size'])[0]
0

精彩评论

暂无评论...
验证码 换一张
取 消