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

时间:2019-06-25 06:44:36

标签: python string list replace

给出两个列表,我想比较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']

预期输出:

lst1 = ['the','[red]','[man]','drank','the','[juice]']

到目前为止我尝试过的事情:

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)

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

感谢您的帮助!

3 个答案:

答案 0 :(得分: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)

输出:

['the', '[red]', '[man]', 'drank', 'the', '[juice]']

转换为set的好处是,无论set包含多少东西,无论花费多少,都要花费大约相同的时间,而同一操作花费的时间list随其大小缩放。

答案 1 :(得分:1)

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

one_lst = ['red','man','juice']
lst1 = ['the','red','man','drank','the','juice']

res=[]

for i in lst1:
    if i in one_lst:
        res.append('{}{}{}'.format('[',i,']'))
    else:
        res.append(i)

print(res)

输出

['the', '[red]', '[man]', 'drank', 'the', '[juice]']

答案 2 :(得分:0)

以下是一个建议:

[x if x not in str1.split(' ') else [x] for x in str2.split(' ')]

输出

  

['the',['red'],['man'],'喝','the',['果汁']]