Sorting list with custom order in Python

有些话、适合烂在心里 提交于 2021-01-27 19:43:08

问题


Hello I currently have two lists, as shown below:

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

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

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

list1.sort(key=list2.index)

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


回答1:


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 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']



回答2:


numpy arrays are really helpful here:

import numpy as np
indices = np.searchsorted(list1, list2) #numpy array [1 0 4 2 3]

Now we have indices that tell the order of names taken from list1. Now we are able to access the output in two ways:

First way (using list comprehension):

list1[i for i in indices]

Second way (using numpy index arrays):

list(np.array(list1)[indices])

Output:

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



来源:https://stackoverflow.com/questions/59237473/sorting-list-with-custom-order-in-python

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