如何使用字典查找替换列表中的元素

时间:2013-06-25 11:10:54

标签: python list replace

鉴于此列表

my_lst = ['LAC', 'HOU', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']

我想根据字典值更改其0th1st值:

def translate(my_lst):
    subs = {
        "Houston": "HOU", 
        "L.A. Clippers": "LAC",

    }

所以列表变成:

['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']

5 个答案:

答案 0 :(得分:10)

如果所有值都是唯一的,那么您应该首先反转dict以获得有效的解决方案:

>>> subs = {
...         "Houston": "HOU", 
...         "L.A. Clippers": "LAC",
... 
...     }
>>> rev_subs = { v:k for k,v in subs.iteritems()}
>>> [rev_subs.get(item,item)  for item in my_lst]
['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']

如果您只是尝试更新所选索引,请尝试:

indexes = [0, 1]
for ind in indexes:
    val =  my_lst[ind]
    my_lst[ind] = rev_subs.get(val, val)

答案 1 :(得分:5)

如果值是唯一的,那么您可以翻转字典:

subs = {v:k for k, v in subs.iteritems()}

然后你可以使用.get()从字典中获取值,以及第二个参数,因为键不在字典中:

print map(subs.get, my_lst, my_lst)

打印:

['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']

答案 2 :(得分:3)

如果您想要更短的内容,可以利用series中的pandas函数

import pandas as pd
A = ['A','B','A','C','D'] #list we want to replace with a dictionary lookup
B = {'A':1,'B':2,'C':3,'D':4} #dictionary lookup, dict values in B will be mapped to entries in A
C = (pd.Series(A)).map(B) #convert the list to a pandas series temporarily before mapping
D = list(C) # we transform the mapped values (a series object) back to a list
# entries in D = [1,2,1,3,4]

答案 3 :(得分:1)

反转dict,然后将查找应用于列表的前2个元素:

subs = {
    "Houston": "HOU", 
    "L.A. Clippers": "LAC",

}

my_lst = ['LAC', 'HOU', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']
my_lst[:2] = map(dict(zip(subs.values(), subs)).get, my_lst[:2])
print my_lst

答案 4 :(得分:0)

这是熊猫的单行...。

df['A'].replace(dict(zip(
        ['SERVICIOS', 'ECON?MICO', 'ECONOMICO', 'EN ESPECIE'],
        ['servicios', 'economico', 'economico', 'en especie'])
                       ),regex=True)