Python如何用字典中的值替换一个列表中的值?

标签 python list dictionary replace

示例:

我的列表是['tree','world','tre','worl']

我的字典是 {'tre':'good','worl':nice}

我的脚本:

def replace(list, dictionary):
    for i in list:
        for k in dictionary:
            list = list.replace(k, dictionary[k])
    return list
print replace(input_file,curaw_dict)

但是每次我收到的结果都是这样的:

goode
niced
good
nice

我怎样才能使它更准确 让它像

tree
world
good
nice

非常感谢

最佳答案

让我们改为列表推导式。

replaced_list = [x if x not in my_dict else my_dict[x] for x in my_list]

我想如果你想要一个你可以做的功能:

replace = lambda my_dict, my_list: [x if x not in my_dict else my_dict[x] for x in my_list]

def replace(my_list, my_dict):
    return [x if x not in my_dict else my_dict[x] for x in my_list]

关于Python如何用字典中的值替换一个列表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45205216/

相关文章:

python - 迁移后Django表不存在

python - 可视化文本分类

python - 如何检查 "' MySQL 服务器是否已经消失'”

python 元组列表排序

python - PCA的主要成分

python - 如何检查 List A 中的元素是否不存在于 Python 的 List B 中?

arrays - 将字符串、整数和数组的 JSON 对象解码到映射中

python - {元组 :NumPy. 数组} 的循环字典

python - 在 Python 中附加到嵌套列表或字典

python - 单行不带括号的打印列表