如何根据另一个列表对列表进行排序? Python [英] How to sort a list according to another list? Python
本文介绍了如何根据另一个列表对列表进行排序? Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,如果我有一个列表:
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]
所以,梅根= 9,贝丝= 6(顺便说一句,这是从字典中获得的)
So Megan = 9 and Beth = 6 (this is from a dictionary by the way)
我如何按字母顺序对名称进行排序,但如何使score_list与名称匹配? 我已经使用冒泡排序方法对数字进行了排序,但没有对字符串进行排序.
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.
推荐答案
您可以使用zip
与元组同时对它们进行排序.排序将按名称进行:
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))
然后
name, score_list = [t[0] for t in tuples], [t[1] for t in tuples]
这篇关于如何根据另一个列表对列表进行排序? Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文