![](/img/trans.png)
[英]Sort a list of lists using descending order, and then if there is a tie breaker, use descending order on another index in python
[英]Sorting 2 lists that are related using zip function in Python, how to sort in descending order?
因此,我正在尝试对2个相关列表进行排序。 一个包含候选人名称,一个包含候选人拥有的投票数( candidate[0]
中的candidate[0]
票数存储在votes[0]
)。
我找到了一种在保持索引匹配的同时对voice []进行降序排序的方法。 例如,如果vote[0]
变为vote[3]
,则candidate[0]
也将成为candidate[3]
。 我使用内置的zip
函数完成了此操作,但是我复制的示例是按升序对列表进行排序的,而我要求它们按降序进行排序。 这是我的清单:
candidates = ['Donald', 'Barack', 'Hillary', 'Mitt']
votes = [9, 7, 1, 3]
并对我使用的列表进行排序:
votes, candidates = (list(t) for t in zip(*sorted(zip(votes, candidates))))
这确实符合我的要求,只是按升序排列,不按降序排列。 我该如何编辑以将列表按降序排序?
您可以只排序list
的zip
并将其reverse
>>> votes = [9, 7, 1, 3]
>>> candidates = ['Donald', 'Barack', 'Hillary', 'Mitt']
>>>
>>> sorted(zip(votes, candidates), key=lambda x: x[0]) # in ascending order
[(1, 'Hillary'), (3, 'Mitt'), (7, 'Barack'), (9, 'Donald')]
>>>
>>> sorted(zip(votes, candidates), key=lambda x: x[0], reverse=True) # in descending order
[(9, 'Donald'), (7, 'Barack'), (3, 'Mitt'), (1, 'Hillary')]
>>> # and if you want it back in order again;
>>> votes, names = zip(*sorted(zip(votes, candidates), key=lambda x: x[0], reverse=True))
>>> votes
(9, 7, 3, 1)
>>> names
('Donald', 'Barack', 'Mitt', 'Hillary')
使用reverse=True
:
candidates = ['Donald', 'Barack', 'Hillary', 'Mitt']
votes = [9, 7, 1, 3]
votes, candidates = (list(t) for t in zip(*sorted(zip(votes, candidates))))
print(sorted(votes, reverse=True))
print(sorted(candidates, reverse=True))
OUTPUT:
[9, 7, 3, 1]
['Mitt', 'Hillary', 'Donald', 'Barack']
要么
candidates = ['Donald', 'Barack', 'Hillary', 'Mitt']
votes = [9, 7, 1, 3]
print(sorted(zip(candidates, votes), reverse=True))
OUTPUT:
[('Mitt', 3), ('Hillary', 1), ('Donald', 9), ('Barack', 7)]
编辑3:
candidates = ['Donald', 'Barack', 'Hillary', 'Mitt']
votes = [9, 7, 1, 3]
votes, candidates = (list(t) for t in zip(*sorted(zip(votes, candidates), reverse=True)))
print(votes)
print(candidates)
OUTPUT:
[9, 7, 3, 1]
['Donald', 'Barack', 'Mitt', 'Hillary']
或者,切片可逆:
candidates = ['Donald', 'Barack', 'Hillary', 'Mitt']
votes = [9, 7, 1, 3]
votes, candidates = (list(t) for t in zip(*sorted(zip(votes, candidates))[::-1]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.