Python:比较和替换list [i]和方括号

swa*_*amz 2 python string replace list

给定两个列表,我想比较list1和list2,并在list1中替换它,并添加方括号。

str1 = "red man juice"
str2 = "the red man drank the juice"

one_lst = ['red','man','juice']
lst1 = ['the','red','man','drank','the','juice']
Run Code Online (Sandbox Code Playgroud)

预期输出:

lst1 = ['the','[red]','[man]','drank','the','[juice]']
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的是:

lst1 = list(str1.split())
for i in range(0,len(lst1)):
    for j in range(0,len(one_lst)):
        if one_lst[j] == lst1[i]:
            str1 = str1.replace(lst1[i],'{}').format(*one_lst)
lst1 = list(str1.split())
print(lst1)
Run Code Online (Sandbox Code Playgroud)

我可以更换它,但是没有括号。

谢谢您的帮助!

gmd*_*mds 7

那就是用低级语言进行的操作。除非您对此有特殊需要,否则在Python中,我将改用一种list理解:

str1 = 'red man juice'
str2 = 'the red man drank the juice'

words_to_enclose = set(str1.split())

result = [f'[{word}]'  # replace with '[{}]'.format(word) for Python <= 3.5
          if word in words_to_enclose 
          else word 
          for word in str2.split()]

print(result)
Run Code Online (Sandbox Code Playgroud)

输出:

['the', '[red]', '[man]', 'drank', 'the', '[juice]']
Run Code Online (Sandbox Code Playgroud)

转换为a的好处set是,set无论a 有多大,都要花费(大约)相同的时间来检查a是否包含某些东西,而对于list规模相同的秤,进行相同操作所花费的时间。