python - 根据 dict 值更改列表中的元素
问题描述
我在 Python 中有一个包含三个不同数字的列表:
myList = [1,2,2,3,1,3,1,2,2,3,1,1,2,3]
我有一个字典:
d = {"one":1, "two":2, "three":3}
是否有一些内置函数(我在想像 map 函数之类的东西)可以在 dict. 到python列表中才能改变它?
预期结果:
myList = ["one", "two", "two", "three", "one", "three"...]
解决方案
恢复字典
>>> reverted_dict = {v: k for k, v in d.items()}
...并在列表理解中使用它:
>>> [reverted_dict[i] for i in myList]
['one', 'two', 'two', 'three', 'one', 'three', 'one', 'two', 'two', 'three', 'one', 'one', 'two', 'three']
map()
如果您愿意,也可以使用该功能:
>>> list(map(reverted_dict.get, myList))
['one', 'two', 'two', 'three', 'one', 'three', 'one', 'two', 'two', 'three', 'one', 'one', 'two', 'three']
推荐阅读
- java - 多次重启后如何唯一标识一个java进程
- python - 如何从熊猫数据框中的一列列表中的列表中随机选择
- android - 无法在 Android Studio 上重新打开组件树
- php - 未定义属性:stdClass::$Unblinking Eternity
- python - Python - 使用 scipy.stats.hypergeom 进行矢量化操作
- php - 如何修复 AWS Lightsail 服务器上的网关超时?
- r - 使用 testthat 检查数据框中的每个变量的 NA 值
- r - 如何分隔字符串并将其作为向量在 R 中读取?
- reactjs - 在 ReactJS 链接中传递和访问参数
- excel - VBA删除活动工作表