How to replace elements in a list using dictionary lookup

前端 未结 5 1419
你的背包
你的背包 2020-12-03 10:37

Given this list

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

I want to change its 0th

相关标签:
5条回答
  • 2020-12-03 11:25

    Reverse the dict, then just apply the lookup to the first 2 elements of your list:

    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
    
    0 讨论(0)
  • 2020-12-03 11:29

    This is a one-line in pandas ....

    df['A'].replace(dict(zip(
            ['SERVICIOS', 'ECON?MICO', 'ECONOMICO', 'EN ESPECIE'],
            ['servicios', 'economico', 'economico', 'en especie'])
                           ),regex=True)
    
    0 讨论(0)
  • 2020-12-03 11:34

    If the values are unique, then you can flip the dictionary:

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

    Then you can use .get() to get the value from a dictionary, along with a second parameter incase the key is not in the dictionary:

    print map(subs.get, my_lst, my_lst)
    

    Prints:

    ['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']
    
    0 讨论(0)
  • 2020-12-03 11:34

    if you want something shorter, you can exploit the series function in 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]
    
    0 讨论(0)
  • 2020-12-03 11:40

    If all values are unique then you should reverse the dict first to get an efficient solution:

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

    If you're only trying to updated selected indexes, then try:

    indexes = [0, 1]
    for ind in indexes:
        val =  my_lst[ind]
        my_lst[ind] = rev_subs.get(val, val)
    
    0 讨论(0)
提交回复
热议问题