Search code examples
pythonlistsorting

how to sort a list in python consisting of monitor resolutions?


I want to sort this list but couldn't find a way to do it.

i/p :

['1152x864', '1920x1080', '1600x900', '1280x1024', '1024x768', '640x480', '720x400', '800x600']

o/p :

['1920x1080', '1600x900', '1280x1024', '1152x864', '1024x768', '800x600', '720x400', '640x480']

Thanks in advance.


Solution

  • TLDR;

    My last approach seems to be the most relevant for your case. When you see a device that states "14-inch screen", they are talking about the diagonal and not the height or width. So, if you want to say that a MacBook 15 > MacBook 13 then thats the one to go for. If you purely want to work with resolution and pixels, then try the second last one which would be more relevant.


    You can use sorted() along with a custom key with lambda function to extract height, width and apply your computation. You will also need reverse=True based on what you are trying to do.

    The lambda function takes each element as x and then extracts the width and/or height using x.split('x')[0] and x.split('x')[1] respectively. Then you can choose to use Pythagoras theorem to get the diagonal OR just product them to get your pixels, etc..

    I try to not use any external libraries such as numpy or math for this. Read more about the sorted function here.

    Sorting by width only -

    enter image description here

    sorted(l, key=lambda x: int(x.split('x')[0]), reverse=True)
    

    Sorting by height only -

    enter image description here

    sorted(l, key=lambda x: int(x.split('x')[1]), reverse=True)
    

    Sorting by Aspect ratio (width/height) -

    enter image description here

    sorted(l, key=lambda x: int(x.split('x')[0])/int(x.split('x')[1]), reverse=True)
    

    Sorting by the number of pixels (width*height) -

    enter image description here

    sorted(l, key=lambda x: int(x.split('x')[0])*int(x.split('x')[1]), reverse=True)
    

    Sorting by monitor screen size (diagonal of the screen) -

    screen size = sqrt((width^2)+(height^2))

    enter image description here

    sorted(l, key=lambda x: (int(x.split('x')[0])**2+int(x.split('x')[1])**2)**(1/2), reverse=True)
    
    ['1920x1080',
     '1600x900',
     '1280x1024',
     '1152x864',
     '1024x768',
     '800x600',
     '720x400',
     '640x480']