给定两个列表,我想比较 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)
我可以替换它,但没有括号。
感谢您的帮助!
最佳答案
这就是你在低级语言中会做的事情。除非您对此有特殊需要,否则在 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
的相同操作所花费的时间与其大小成比例。
关于Python:用括号比较和替换列表[i],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56748220/