Find values from a List and Replace in another list - Python

Asked

Viewed 209 times

-1

I am trying to search for elements of the A list in List B and replace it with another value if this element is found. How can I do this?

A = ["Leao" , "Lobo" , "Largarto"]
B = ["Cachorro" , "Leao" , "Cobra" , "Girafa" , "Lobo" , "Largarto"]

Replace element of A in B by the word "Manga" and the result would be

C = ["Cachorro" , "Manga" , "Cobra" , "Girafa" , "Manga" , "Manga"]

Searching I only managed to find this code, but then I would have to every time write what I need to replace:

B = [item.replace("Leao", "Manga") for item in B]

2 answers

5

The best way is to go through the list B and for each value check if it is in A; if it is, return the value to be replaced, but return the value itself.

With list comprehension it becomes quite simple:

C = [b if b not in A else 'Manga' for b in B]

In the stretch for b in B you go through list B; in b if b not in A else 'Manga' you keep the value of b when he’s not in A or "Manga" when he has.

  • Thank you very much, it worked perfectly.

2

Another way to do it is to create a dictionary with the key being the element you replace and the value of that key the new element:

A = {
# "item na array B":"novo valor",
    "Leao":"Manga" ,
    "Lobo":"Banana" ,
    "Largarto":"Abacaxi"
}
B = ["Cachorro" , "Leao" , "Cobra" , "Girafa" , "Lobo" , "Largarto"]


C = [ (A[item] if item in A else item) for item in B ]

print( C )
# SAIDA DO PRINT:
# ['Cachorro', 'Manga', 'Cobra', 'Girafa', 'Banana', 'Abacaxi']

See the code working on ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.