How to replace elements in a list using dictionary lookup

前端 未结 5 1443
你的背包
你的背包 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: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)
    

提交回复
热议问题