3

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.

Eliott Reed
  • 351
  • 1
  • 4
  • 12
  • 1
    Does this answer your question? [Sorting list based on values from another list](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – Soroosh Noorzad Apr 24 '21 at 10:38

3 Answers3

3

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:\Users\albin\Documents\codebase>python test.py
(('Boris', 'Amanda', 'Charlie', 'Chris'), (55, 43, 35, 35))
Albin Paul
  • 3,330
  • 2
  • 14
  • 30
0

You can first sort in descending order by using the key (1/age, name) (i.e. ascending in age and descending in name) and then reverse the result (i.e. descending in age and ascending in name):

def my_sort(names, ages):
    tmp = sorted(zip(ages, names), reverse=True, key=lambda x: (1/x[0], x[1]))
    ages, names = zip(*reversed(tmp))
    return names, ages
a_guest
  • 34,165
  • 12
  • 64
  • 118
0

You can use this :

def list_sorting(l1, l2):
    # First zip your code, and sort it:
    res = list(sorted(zip(l2, l1)))
    # Then unzip your code and send it back as a list of lists. Done!
    return [[i for i, j in res], [j for i, j in res]]


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

The result :

[[35, 35, 43, 55], ['Charlie', 'Chris', 'Amanda', 'Boris']]
Soroosh Noorzad
  • 503
  • 1
  • 6
  • 18