如何使用字典查找替换列表中的元素 [英] How to replace elements in a list using dictionary lookup

查看:360
本文介绍了如何使用字典查找替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供此列表

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

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

I want to change its 0th and 1st values according to the dictionary value:

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

推荐答案

如果所有值都是唯一的,则应首先反转dict以得到有效的解决方案:

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)

这篇关于如何使用字典查找替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆