-1

I have limited knowledge of python, so this is probably a bad question, but I am trying to go through a list and replace each item in the list with another item based on what the original item is.

For example I have a list ['A', 'B', 'C', 'B'], and I want to go through and replace each item with a corresponding item so it ends up as ['D', 'E', 'F', 'E']

Thanks!

jottbe
  • 4,228
  • 1
  • 15
  • 31
  • 1
    make a dictionary of the corresponding items with the key of the original item, then loop through the list and replace each item with the its corresponding value in the dictionary – Ironkey Dec 01 '20 at 15:39
  • 1
    Look at [this](https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list) question. – ghostshelltaken Dec 01 '20 at 15:41
  • ^ specifically [this](https://stackoverflow.com/a/63363124/11748253) answer – Ironkey Dec 01 '20 at 15:43

2 Answers2

0

When you want lookups, you should use dictionaries:

replacements = {
    "A": "D",
    "B": "E",
    "C": "F"
}

original = ["A", "B", "C", "B"]
replaced = [replacements[x] for x in original]
print(replaced) # ["D", "E", "F", "E"]

The [... for x in ...] syntax is a list comprehension.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0
dic_correspondance = {"a":"d","b":"e","c":"f"}
for i in liste:
   liste[i] = dic_correspondance.get(liste[i])

First you create a dictionary with equivalences, you will have key and value peers. So the key will allow you to have the equivalence. Then you browse your list, and for each element of your list accessible via its index you use the get method of the dictionary to get the key of the current value (the current element). Then you reassign what is in the current index with the equivalence retrieve with get.

jdenozi
  • 212
  • 1
  • 11