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?

3
  • 4
    Does this answer your question? Sorting list based on values from another list? Commented Dec 8, 2019 at 16:36
  • key=lambda x: list2.index(x[0]) Commented Dec 8, 2019 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 Commented Dec 8, 2019 at 16:47

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

2 Comments

I seem to get "TypeError: 'list' object is not callable" which is something to do with the out line
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 listvariable. In an interactive session or Jupyter, del list will return it to its original meaning.
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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.