示例:
我的列表是['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/