所以,我正在尝试对 2 个相关列表进行排序。一个包含候选人姓名,另一个包含候选人拥有的票数(candidate[0]
中的候选人的选票存储在votes[0]
中(。
我找到了一种按降序对 vote[] 进行排序的方法,同时保持索引匹配。例如,如果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))
输出:
[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))
输出:
[('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)
输出:
[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]))