Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get lst1 to be alphabetical while being in the same order as lst2

Input:

list_sorting(['Chris','Amanda','Boris','Charlie'],[35,43,55,35])

Output:

['Boris', 'Amanda', 'Charlie', 'Chris'], [55, 43, 35, 35] 

My Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def list_sorting(lst1, lst2):
    zipped_pairs = zip(lst2, lst1)
    sorted_pairs = reversed(sorted(zipped_pairs))
    
    tuples = zip(*sorted_pairs)
    lst2, lst1 = [ list(tuple) for tuple in tuples]
    
    return lst1, lst2

Right now this returns:

['Boris', 'Amanda', 'Chris', 'Charlie'], [55, 43, 35, 35]

So lst2 is how I need it but still need lst1 to be alphabetical.

>Solution :

You can do a small trick to get what you need. Since you want numbers to be descendent and words to be ascendent, you can make it work ascendently and negate numbers:

lst1 = ['Boris', 'Amanda', 'Charlie', 'Chris']
lst2 = [55, 43, 35, 35]

def list_sorting(lst1, lst2):
    out = sorted(zip(lst1, lst2), key=lambda el: (-el[1], el[0]), reverse=False)
    return list(map(list, zip(*out)))

list_sorting(lst1, lst2)

Output:

[('Boris', 'Amanda', 'Charlie', 'Chris'), (55, 43, 35, 35)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading