Python – Loop to replace elements in string with second element of elements in second string?

Question:

I am trying to replace elements that are in one string with the second element (also string type) of elements in a second string.

a_list and replace are short versions of the lists that I am working with. I want to replace the elements in the first list a_list with the first elements of each list in the second list, if the second element (POS tags) of each list in the second list matches and then check the rest of the list.

Here is an example part of the lists that I am working with and my not working function:

a_list = ["JJ","MM","JJ"]

replace = [['Innovative', 'JJ'],['methods', 'NNS'],['test', 'MM'],['extra', 'JJ']]

new_list = []

for item in a_list:
    if a_list[i] == replace[i][1]:
        new_list.append(item.replace(replace[i][1], replace[i][0]))
        
    else:
        new_list.append(item)

print(new_list)  

['JJ', 'MM', 'JJ']

what I want: ['Innovative', "test", "extra"]

a_list, a_list[1], replace, replace[1], and replace[1][1] are all strings. They were tuples but those were harder for me to work with.

Not sure how to remove that specific string after it was used to replace and not sure how to iterate over both strings. replace is a lot longer than a_list. I have been working on this for a couple of hours now I’m sure there is something that can do this – just need help, it seems so close! There are many similar questions but I have tried and they have not worked for me

Thank you!

Asked By: lex

||

Answers:

You have to iterate over replace too. If you find a matching entry then add the corresponding value to your list, delete this entry from replace and break from the inner loop. If you don’t find a match, then add your original item. One of the cases where forelse comes in handy.

a_list = ["JJ","MM","JJ"]
replace = [['Innovative', 'JJ'],['methods', 'NNS'],['test', 'MM'],['extra', 'JJ']]
new_list = []
for item in a_list:
    for i, (value, key) in enumerate(replace):
        if key == item:
            new_list.append(value)
            del replace[i]
            break
    else:
        new_list.append(item)

print(new_list)

Result:

['Innovative', 'test', 'extra']

If you define your list with a_list = ["Hello", "JJ", "MM", "JJ", "JJ"] you’ll get ['Hello', 'Innovative', 'test', 'extra', 'JJ']. There is no replacement for "Hello" and there’s no replacement left for the last "JJ".

Answered By: Matthias

The @Matthias answer well responds to the original question. I’d like to suggest a variation to that code using a modification on how the replacements are defined which might be useful in wider use:

a_list = ["JJ","MM","JJ"]
new_list = []
replacements = {'JJ': ['Innovative', 'extra'], 'NNS' : ['methods'], 'MM': ['test']}

for item in a_list:
    x = replacements.get(item, None)
    if x and x[0]:
        new_list.append(x[0])
        del x[0]
    else:
        new_list.append(item)
Answered By: user19077881
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.