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

基于自定义字典映射列表中的值-Python,python,python-3.x,Python,Python 3.x,我有一个数字列表: 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,....] 我所

我有一个数字列表:

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。

看看这个:

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

谢谢你的映射,我一直在寻找类似的东西。 就速度而言(在我的列表中(35k条记录)):

  • 列表理解(@Arvin Kushwaha):
    a=[cust_dict[i]代表a中的i]
    -->3毫秒
  • Lambda映射(@Arvin Kushwaha):
    a=list(映射(Lambda x:cust_dict[x],a))
    -->5.54ms
  • Dict-get映射(@Olvin-Roght):
    a=list(map(cust_-Dict.get,a)
    -->2ms
  • PS:pandas映射耗时9毫秒(将pd.series转换回列表)
    谢谢大家!

    对于35K个项目,我会使用NumPy数组,或者在本文中使用熊猫系列(这显然忽略了您问题中提到的“纯Python”):


    但是,根据进一步的需要和使用情况,您可能不想将该系列转换回列表。

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

    列表理解!
    a=[cust_dict[i]for i in a]
    您可以使用列表理解,但它不会给您显著的提升。映射!
    a=list(map(lambda x:cust_dict[x],a))
    @ArvinKushwaha,
    a=list(map(cust_dict.get,a))
    会好得多。@ArvinKushwaha,
    lambda
    无论如何都会慢得多。根据进一步的需要,您可能希望将内容保留为数组或序列,而不是再次使用列表。列表可以很快,但在某个时候,数组或序列会超过Python列表。如果我有额外的处理,我同意让内容进入系列或数组。@Pdeuxa,如果你真的对执行时间很着迷,你可以用
    cust\u list=[None',one',two',three',four']
    替换
    list(map(cust\u list.\uu getitem\uuuuuu,a))
    ,应该快一点。
    >>> 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']