Home > Back-end >  Return Object with Greater Parameter
Return Object with Greater Parameter

Time:01-17

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)

CodePudding user response:

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.

  •  Tags:  
  • Related