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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With