映射基于自定义Dictionary-Python的列表中的值



我有一个数字列表:

a = [4,4,4,4,4,4,4,4,4,........................,4,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4]

我想根据自定义字典转换值,例如:

cust_dict ={4:'four',1:'one',2:'two',3:'three'}

要获得以下内容:

a= [four,four,four,four,four.....,four, three,two,....]

我所做的唯一代码是使用for循环:

for i in range(len(a)):
a[i] = cust_dict[a[i]]

有没有一种更有效的方法(在纯python中(,从而避免for循环?对于35k个项目的列表,我用这个代码花了大约4ms。

谢谢你的映射,我正是在寻找这样的东西。就速度而言(在我的列表中(35k个条目((:

  1. 列表理解(@Arvin Kushwaha(:a = [cust_dict[i] for i in a]->3毫秒
  2. Lambda映射(@Arvin Kushwaha(:a = list(map(lambda x: cust_dict[x], a))->5.54毫秒
  3. Dict-get映射(@Olvin Roght(:a=list(map(cust_dict.get, a)->2毫秒

PS:pandans映射耗时9ms(将pd系列转换回列表(谢谢大家!

对于35K项,我会使用NumPy数组,或者在这种情况下,使用Pandas系列(这显然忽略了问题中提到的"纯Python"(:

>>> import pandas as pd
>>> a = [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 3]
>>> cust_dict ={4:'four',1:'one',2:'two',3:'three'}
>>> s = pd.Series(a)
>>> s.map(cust_dict).tolist()
['four', 'four', 'four', 'four', 'four', 'four', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'two', 'two', 'two', 'four', 'four', 'four', 'one', 'one', 'one', 'one', 'two', 'two', 'two', 'three']

但您可能不想将该系列转换回列表,具体取决于进一步的需求和使用情况。

看看这个:

a= [4,4,4,4,4,4,4,4,4,4,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4]
cust_dict ={4:'four',1:'one',2:'two',3:'three'}
output = list(map(lambda x: cust_dict[x], a))
print(output)
# ['four', 'four', 'four', 'four', 'four', 'four', 'four', 'four', 'four', 'four', 'three', 'two', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'three', 'four']

a[:]=map(lambda x:cust_dict[x],a(

最新更新