在Python中按自定义顺序排序列表 [英] Sorting list with custom order in Python

查看:53
本文介绍了在Python中按自定义顺序排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我目前有两个列表,如下所示:

Hello I currently have two lists, as shown below:

list1 = [Alpha, Beta, Charlie, Delta, Echo] 

list2 = [B, A, E, C, D]

我想使用list2对list1进行排序,我尝试使用:

I would like to use list2 to sort list1, I have tried using:

list1.sort(key = list2.index)

list1.sort(key=list2.index)

但是,在单词中找不到字母.有没有一种方法可以对list1进行排序而不使用其全名?

However, the letters are unable to be found within the word. Is there a way to sort list1 without each of their full name?

推荐答案

必须按单词首字母排序:

You must sort according to the first letter of the words:

list1 = ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo'] 

list2 = ['B', 'A', 'E', 'C', 'D']

out = list(sorted(list1, key=lambda word: list2.index(word[0])))
print(out)
# ['Beta', 'Alpha', 'Echo', 'Charlie', 'Delta']

但是,每次

index 都必须在 list2 上进行迭代.首先建立一个给出每个字母的索引的字典可能会更有效,以便在排序时我们可以在O(1)中找到索引:

index will have to iterate on list2 each time though. It might be more efficient to build a dict giving the index of each letter first, so that we can find the indices in O(1) when sorting:

list1 = ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo'] 

list2 = ['B', 'A', 'E', 'C', 'D']
dict2 = {letter: index for index, letter in enumerate(list2)}

out = list(sorted(list1, key=lambda word: dict2[word[0]]))
print(out)
# ['Beta', 'Alpha', 'Echo', 'Charlie', 'Delta']

这篇关于在Python中按自定义顺序排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆