根据字典值更改列表中的元素

时间:2021-02-03 23:58:58

标签: python

我有一个包含三个不同数字的 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"...]

2 个答案:

答案 0 :(得分:2)

恢复字典

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

答案 1 :(得分:0)

使用熊猫和地图

如果你想使用pandas.Series和map,那么你可以这样做:

myList = [1,2,2,3,1,3,1,2,2,3,1,1,2,3]
d = {1:"one", 2:"two", 3:"three"}
import pandas as pd
newlist = pd.Series(myList).map(d).tolist()
print (newlist)

注意这里我翻转了字典 key:values。

使用列表理解

输出将是:

['one', 'two', 'two', 'three', 'one', 'three', 'one', 'two', 'two', 'three', 'one', 'one', 'two', 'three']

或者,您可以这样做:

newlist = [d[i] if i in d else None for i in myList ]
print (newlist)

输出将是:

['one', 'two', 'two', 'three', 'one', 'three', 'one', 'two', 'two', 'three', 'one', 'one', 'two', 'three']
相关问题