实现这一目标的最佳途径是什么:
original_list = ["word_1", "word_2", "word"]
replacements = {
'word_1': 'something',
'word': 'number'
}
updated_list = replace_in_list(original_list, replacements)
,其中
updated_list == ["something", "word_2", "number"]
答案 0 :(得分:5)
使用列表推导来访问替换dict键,默认值为原始字符串(如果找不到)(使用get
):
updated_list = [replacements.get(x,x) for x in original_list]
答案 1 :(得分:1)
一衬垫:
>>> [replacements[w] if w in replacements else w for word in original_list]
['something', 'word_2', 'number']