lyr*_*pha 3 python dictionary replace list
例子:
\n\n我的清单是['tree'\xef\xbc\x8c'world'\xef\xbc\x8c'tre'\xef\xbc\x8c'worl']
我的字典是{'tre':'good','worl':nice}
我的脚本:
\n\ndef replace(list, dictionary):\n for i in list:\n for k in dictionary:\n list = list.replace(k, dictionary[k])\n return list\nprint replace(input_file,curaw_dict)\nRun Code Online (Sandbox Code Playgroud)\n\n但每次我收到的结果都是像\xef\xbc\x9a
\n\ngoode\nniced\ngood\nnice\nRun Code Online (Sandbox Code Playgroud)\n\n我怎样才能让它更准确\n让它像
\n\ntree\nworld\ngood\nnice\nRun Code Online (Sandbox Code Playgroud)\n\n多谢
\n让我们将其改为列表理解。
replaced_list = [x if x not in my_dict else my_dict[x] for x in my_list]
Run Code Online (Sandbox Code Playgroud)
我想如果你想要一个功能,你可以这样做:
replace = lambda my_dict, my_list: [x if x not in my_dict else my_dict[x] for x in my_list]
Run Code Online (Sandbox Code Playgroud)
或者
def replace(my_list, my_dict):
return [x if x not in my_dict else my_dict[x] for x in my_list]
Run Code Online (Sandbox Code Playgroud)