How to sort a list according to another list? Python

人盡茶涼 提交于 2019-12-20 03:23:50

问题


So if I have one list:

name = ['Megan', 'Harriet', 'Henry', 'Beth', 'George']

And I have another list where each value represents the names in the right order

score_list = [9, 6, 5, 6, 10]

So Megan = 9 and Beth = 6 (this is from a dictionary by the way)

How would I sort name alphabetically but keep the score_list matching name? I have done the with sorting numbers using the bubble sort method but not strings.


回答1:


You can sort them at the same time as tuples by using zip. The sorting will be by name:

tuples = sorted(zip(name, score_list))

And then

name, score_list = [t[0] for t in tuples], [t[1] for t in tuples]



回答2:


One obvious approach would be to zip both the list sort it and then unzip it

>>> name, score = zip(*sorted(zip(name, score_list)))
>>> name
('Beth', 'George', 'Harriet', 'Henry', 'Megan')
>>> score
(6, 10, 6, 5, 9)



回答3:


The correct way if you have a dict is to sort the items by the key:

name = ['Megan', 'Harriet', 'Henry', 'Beth', 'George']

score_list = [9, 6, 5, 6, 10]
d = dict(zip(name, score_list))

from operator import itemgetter
print(sorted(d.items(), key=itemgetter(0)))
[('Beth', 6), ('George', 10), ('Harriet', 6), ('Henry', 5), ('Megan', 9)]



回答4:


Consider a third-party tool more_itertools.sort_together:

Given

import more_itertools as mit


name = ["Megan", "Harriet", "Henry", "Beth", "George"]
score_list = [9, 6, 5, 6, 10]

Code

mit.sort_together([name, score_list])
# [('Beth', 'George', 'Harriet', 'Henry', 'Megan'), (6, 10, 6, 5, 9)]

Install more_itertools via > pip install more_itertools.



来源:https://stackoverflow.com/questions/29876580/how-to-sort-a-list-according-to-another-list-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!