首页 > 解决方案 > Python - How to sort a list with another list that contains new indices for 1st list

问题描述

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?

标签: pythonlist

解决方案


如果您可以导入 numpy,请使用它!

import numpy as np

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

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

否则:

newList = [oldList[index] for index in indexes]

推荐阅读