简体   繁体   English

Python - 对 2 个列表进行排序 - 升序和降序并返回为 2 个列表

[英]Python - Sorting 2 Lists - both ascending and descending order and returning back as 2 lists

Write a function that takes 2 lists.编写一个包含 2 个列表的 function。 lst1 is a list of towns, lst2 sales numbers for the towns. lst1 是城镇列表,lst2 是城镇的销售数字。 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). function需要返回这些列表的副本,以便它们都按销售顺序排序(降序,即lst1中的城镇名称也需要按照lst2中的销售额排序)。 If two or more towns have the same sales numbers then these towns need to be ordered by their names also (ascending order: AZ)如果两个或多个城镇的销售数字相同,那么这些城镇也需要按名称排序(升序:AZ)

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM