Skip to content
Advertisement

I need to sort two lists of tuples in different orders depending on whether elements in the tuples are equal or not

I have two possible lists, one is the name and the second is the age. my function needs to return copies of these lists such that they are both sorted in order of age (descending order) (ie the names of employees in the lst1 are also required to be ordered according to their ages in lst2). If two or more employees have the same age then these employees need to be ordered by their names also (this time in ascending order: A-Z).

here is my code so far. I am able to produce the two lists. But I am not sure how to change the order of the names that have the same age in the oppiste order to the rest o the lists. I know one should use a loop but not sure how to get going.

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

def list_sorting(lst1,lst2):
    zipped=zip(lst2,lst1)
    sorted_pairs= sorted(zipped,reverse=True)   
    tuples=zip(*sorted_pairs)
    list1,list2 = [ list(tuple) for tuple in tuples]
    return list2,list1

I get the output:

([‘Boris’, ‘Amanda’, ‘Chris’, ‘Charlie’], [55, 43, 35, 35])

but in order for it to be correct, chris and charlie need to swap places.

Advertisement

Answer

You just need one key with a tuple. The tuple contains the negative of the age and the name. So sorting the negative ages ascendingly will result in sorting the ages descendingly. And along with that names are sorted ascendingly.

def list_sorting(lst1,lst2):
    zipped=zip(lst2,lst1)
    sorted_pairs = sorted(zipped, key= lambda x: (-x[0], x[1]))   
    ages, names = list(zip(*sorted_pairs))
    return names, ages

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

OUTPUT

(base) C:UsersalbinDocumentscodebase>python test.py
(('Boris', 'Amanda', 'Charlie', 'Chris'), (55, 43, 35, 35))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement