[英]Python 3.x — sort one list based on another list and then return both lists sorted
Problem: I would like to sort one list based on another list and then return both lists sorted.问题:我想根据另一个列表对一个列表进行排序,然后返回已排序的两个列表。
I'm doing it like this:我这样做是这样的:
points = [4,7,3,2,7]
candidates = ['a', 'b', 'c', 'd', 'e']
ordered_candidates = [x for _, x in sorted(zip(points, candidates), reverse=True)]
ordered_points = sorted(points, reverse=True)
Question : Is it possible to merge the last two lines into one line?问题:是否可以将最后两行合并为一行?
I found question: Sorting list based on values from another list?我发现了问题: 根据另一个列表中的值对列表进行排序? but it's not exactly what I'm asking for.
但这并不是我想要的。
Is it possible to merge the last two lines into one line?
是否可以将最后两行合并为一行?
Yes it is.是的。
ordered_candidates
excludes the points from the result, since you only choose the candidates with [x for _, x in...]
. ordered_candidates
从结果中排除分数,因为您只选择具有[x for _, x in...]
的候选人。 This basically only selects the second item from each tuple.这基本上只从每个元组中选择第二项。 Additionally,
ordered_points
sorts only the points.此外,
ordered_points
仅对点进行排序。 They both also sort in reverse with reverse=True
.它们也都使用
reverse=True
排序。
Seems like you can just modify ordered_candidates
to include both items in the (point, candidate)
pairs.似乎您可以修改
ordered_candidates
以将这两个项目都包含在(point, candidate)
对中。
>>> points = [4,7,3,2,7]
>>> candidates = ['a', 'b', 'c', 'd', 'e']
>>> sorted(zip(points, candidates), reverse=True)
[(7, 'e'), (7, 'b'), (4, 'a'), (3, 'c'), (2, 'd')]
It is possible to do this by:可以通过以下方式做到这一点:
points = [4,7,3,2,7]
candidates = ['a', 'b', 'c', 'd', 'e']
ordered_candidates, ordered_points = zip(*[(p, c) for p, c in sorted(zip(points, candidates), reverse=True)])```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.