Write a function that takes 2 lists. lst1 is a list of towns, lst2 sales numbers for the towns. The function needs to return copies of these lists such that they are both sorted in order of sales (descending order, ie the names of towns in the lst1 are also required to be ordered according to their sales in lst2). If two or more towns have the same sales numbers then these towns need to be ordered by their names also (ascending order: A-Z)
My code:
def sort_lists(lst1, lst2):
tuples_list = list(zip(lst1, lst2))
sorted_list = sorted(tuples_list, key = lambda x:(-x[1], x[0]))
unzipped_list = zip(*sorted_list)
return (list(unzipped_list))
Test data used by auto-marker:
print(list_sorting(['Eugene', 'Phoenix', 'Peoria', 'Ashwood', 'Buxton', 'Crawley', 'Parkdale'],
[45,23,21,14,8,12,23]))
Expected answer:
(['Eugene', 'Parkdale', 'Phoenix', 'Peoria', 'Ashwood', 'Crawley', 'Buxton'], [45, 23, 23, 21, 14, 12, 8])
My answer:
[('Eugene', 'Parkdale', 'Phoenix', 'Peoria', 'Ashwood', 'Crawley', 'Buxton'), (45, 23, 23, 21, 14, 12, 8)]
I have already got the question wrong in the quiz. But this code is used in the next question, so if I can't figure it out I will get that wrong as well.
My answer has the sorting correct, but I have a list of tuples as my result. I thought I was zipping the lists, sorting them and then unzipping to become lists again. But I have done something wrong.
You need to change the sub tuple to list and the list with all items to tuple. Replace
return (list(unzipped_list))
With
return tuple(list(item) for item in unzipped_list)
# output: (['Eugene', 'Parkdale', 'Phoenix', 'Peoria', 'Ashwood', 'Crawley', 'Buxton'], [45, 23, 23, 21, 14, 12, 8])