-1

I have a list like this:

original_list = ['Atlanta', 'New York', 'Miami', 'Chicago']

and a second list, that contains the indices that the 1st list should be sorted to:

index_list = [1, 3, 0, 2]

The result should be

new_list = ['New York', 'Chicago', 'Atlanta', 'Miami']

I tried using the "Key" parameter of Python's "Sorted" function , but can't get it to work. Is there a way to do it?

  • Something like this: `new_list = [e[1] for e in sorted(zip(index_list, original_list), reverse=True)]`? – Matthias Mar 20 '20 at 14:20
  • Working with the `key` parameter of `sorted`isn't the best idea: `new_list = list(sorted(original_list, key=lambda e: index_list[original_list.index(e)], reverse=True))` – Matthias Mar 20 '20 at 14:25

1 Answers1

1

If you can import numpy, just use it !

import numpy as np

oldList = np.array(['Atlanta', 'New York', 'Miami', 'Chicago'])

indexes = [1, 3, 0, 2]
newList = oldList[indexes]

Otherwise:

newList = [oldList[index] for index in indexes]
rambi
  • 1,013
  • 1
  • 7
  • 25