Python: comparing and replacing list[i] with brackets

Viewed 78

Given two lists, I want to compare list1 and list2, and replace it within list1, and add brackets.

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

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

expected output:

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

What I tried so far:

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)

I'm able to replace it, but just without brackets.

Thanks for the help!

3 Answers

That is what you would do in a lower-level language. Unless you have a specific need for this, in Python, I would instead use a list comprehension:

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)

Output:

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

The benefit of conversion to a set is that it takes (roughly) the same time to check if a set contains something regardless of how large it is, whereas the time taken for the same operation for a list scales with its size.

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)

output

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

Here is a one liner suggestion:

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

Output

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

Related