小编swa*_*amz的帖子

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

给定两个列表,我想比较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)

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

谢谢您的帮助!

python string replace list

2
推荐指数
1
解决办法
50
查看次数

标签 统计

list ×1

python ×1

replace ×1

string ×1