Rab*_*dra 2 python list-comprehension python-3.x
我有一个文本和一个列表。
text = "Some texts [remove me] that I want to [and remove me] replace"
remove_list = ["[remove me]", "[and remove me]"]
Run Code Online (Sandbox Code Playgroud)
我想替换字符串中列表中的所有元素。所以,我可以这样做:
for element in remove_list:
text = text.replace(element, '')
Run Code Online (Sandbox Code Playgroud)
我还可以使用正则表达式。但这可以在列表理解或任何单行中完成吗?
您可以使用functools.reduce:
from functools import reduce
text = reduce(lambda x, y: x.replace(y, ''), remove_list, text)
# 'Some texts that I want to replace'
Run Code Online (Sandbox Code Playgroud)