首页 > 解决方案 > 根据 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"...]

标签: python

解决方案


恢复字典

>>> 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']

推荐阅读