-1

Input:

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

Output:

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

My Code:

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.

lemon
  • 14,875
  • 6
  • 18
  • 38

2 Answers2

1

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)]
lemon
  • 14,875
  • 6
  • 18
  • 38
  • How would you get the output in lists rather than tuple – Reece Borchardt May 12 '22 at 10:50
  • You can just add a `map(list, zip(*out))` to it. Updated the answer. – lemon May 12 '22 at 10:51
  • 1
    figured it out, I needed to return lst1 and lst2 individually,```def list_sorting(lst1, lst2): out = sorted(zip(lst1, lst2), key=lambda el: (-el[1], el[0]), reverse=False) tuples = zip(*out) lst1, lst2 = [ list(tuple) for tuple in tuples] return lst1, lst2``` thanks for the help – Reece Borchardt May 12 '22 at 11:03
1

If I understand correctly you wanna have the first list sorted by alphabetical order and the second one with the number associated to the name in the same index as the name? If yes you might do that:

def list_sorting(lst1, lst2):
    zipped_pairs = list(zip(lst1, lst2))
    zipped_pairs.sort()
    lst1 = [a for a,b in zipped_pairs]
    lst2 = [b for a,b in zipped_pairs]
    return lst1,lst2
  • Nah I need it the other way around, so sorted by the numbers descending(lst2) and then the names associated with the numbers, but if the number is the same then the names need to be alphabetical. – Reece Borchardt May 12 '22 at 10:55