问题
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