python - 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?
解决方案
如果您可以导入 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]
推荐阅读
- date - 使用 PostgreSQL (AWS Redshift) 将 Qlik Sense 日期选择器扩展的日期格式从“M/D/YYYY”更改为“DD/MM/YYYY”
- powershell - 如何将文件夹层次结构转换为一台服务器上的共享并从另一台服务器复制权限?
- python-3.x - 将行从文本拆分为键和值,并根据键搜索值
- python-3.x - 如何从 OCR 图像中提取布局信息
- javascript - 克隆没有值的输入
- mysql - 查询选择仅在某一年购买的客户
- java - Maven nar插件:nar文件不在依赖项目的类路径中
- mule - Dataweave(嵌套)映射条件映射
- android - Android Q访问非SDK接口-Landroid/widget/AbsListView;->mSelectorPosition:I(greylist-max-p,反射,拒绝)
- asp.net-core - 向 .NET Core 3 应用程序添加身份服务器身份验证失败,并显示“未指定密钥类型”。