2

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?

Zoe
  • 49
  • 3
  • 4
    Does this answer your question? [Sorting list based on values from another list?](https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – Joshua Nixon Dec 08 '19 at 16:36
  • `key=lambda x: list2.index(x[0])` – Mad Physicist Dec 08 '19 at 16:36
  • 1
    You say you want to sort `list1` according to `list2` but never state how exactly. Try to be more clear and add example output in your questions, it will help more people answer it – Tomerikoo Dec 08 '19 at 16:47

2 Answers2

4

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']
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • I seem to get "TypeError: 'list' object is not callable" which is something to do with the out line – Zoe Dec 08 '19 at 17:02
  • 1
    You have probably used the variable name 'list' for a list before in your code, something like `list = [...]`. You should avoid using the names of builtin functions as variable names. If this is in a script, change the name of your `list`variable. In an interactive session or Jupyter, `del list` will return it to its original meaning. – Thierry Lathuille Dec 08 '19 at 17:05
0

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

mathfux
  • 5,759
  • 1
  • 14
  • 34