Issue
I have two images: one
and two
. I want to determine which is the biggest and smallest and assign them to big
and small
respectively. What is the cleanest and pythonic solution?
My solution is as follows:
one = Image.open(url)
two = Image.open(url)
big, small = (one, two) if one.width > two.width else (two, one)
Solution
If you are looking for a more pythonic approach, you could consider using the power of sorted
to check which file is larger. Advantage of this is that it can easily be expanded to work for a list of images rather than just comparing two items.
images = [Image.open(url1), Image.open(url2), Image.open(url3)]
sorted_images = sorted(images, key=lambda img: img.width, reverse=True)
big, second_biggest = sorted_images[0:2]
The above example shows how you can use the width
attribute of the class instances to sort the images from largest to smallest. reverse=True
tells sorted
to sort the items in largest-smallest order.
The final row just gets the largest two elements from the list and stores them in their own variables.
Answered By - scotty3785
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.