konrad
konrad

Reputation: 3706

iterate through list while looking for matching elements from a different list in python

I have a list of some random strings ex:

list_test = ["adam", "adam", "lori", "conrad", "lori", "adam"]

Then i also have two lists, one that i want to test for matches agains and one that will determine what to replace items with.

sReplace = ["adam", "lori"]
sReplaceWith = ["carol", "robert"]

what i want to do is search list_test if any item on that list matches any item in sReplace if it does replace it with item from sReplaceWith from a matching index number ex.

final_list = ["carol", "carol", "robert", "conrad", "robert", "carol"]

Any idea how one would do that?

Upvotes: 1

Views: 82

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

list_test = ["adam", "adam", "lori", "conrad", "lori", "adam"]
sReplace = ["adam", "lori"]
sReplaceWith = ["carol", "robert"]

print([sReplaceWith[sReplace.index(x)] if x in sReplace else x for x in list_test ])
['carol', 'carol', 'robert', 'conrad', 'robert', 'carol']

Add the element at the corresponding index with sReplaceWith[sReplace.index(x)] if x is in the to be replaced list or else just add x to the list

Upvotes: 2

ErlVolton
ErlVolton

Reputation: 6784

Done without dictionaries:

list_test = ["adam", "adam", "lori", "conrad", "lori", "adam"]
sReplace = ["adam", "lori"]
sReplaceWith = ["carol", "robert"]
for list_index in range(0, len(list_test)):
    list_item = list_test[list_index]
    if list_item in sReplace:
        replace_with = sReplaceWith[sReplace.index(list_item)]
        list_test[list_index] = replace_with
print list_test

Output:

['carol', 'carol', 'robert', 'conrad', 'robert', 'carol']

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

I'd make a dictionary with the Replace as the key and the ReplaceWith as the value.

replacements = dict(zip(sReplace, sReplaceWith))

>>> replacements
{'adam': 'carol', 'lori': 'robert'}

Then in a list comprehension, you can use get, which will look up the replacement from the dictionary, and if not present will use the original word.

final_list = [replacements.get(i,i) for i in list_test]

>>> final_list
['carol', 'carol', 'robert', 'conrad', 'robert', 'carol']

Upvotes: 4

Related Questions