Home > Mobile >  replace multiple values of a list with one call python
replace multiple values of a list with one call python

Time:09-16

Given an initial list, I want to change the list using one function call : This:

A=[cat,dog,ostritch]

To This:

  A=[sal,fred,martin]

I understand we can do

A.replace('cat', 'sal')
A.replace('dog', 'fred')

I would like to make some sort of mapping ie so I can just call the replace function only once. ie:

replace mapping=[cat:sal,dog:fred, ostritch:martin]
A.replace(A,replace_mapping)

CodePudding user response:

Implement the mapping with a dictionary.

mapping = {cat:sal,dog:fred, ostritch:martin}
A = [mapping.get(i, i) for i in A]

mapping.get(i, i) will get the corresponding value from mapping, and default to the original value if there's no such entry.

CodePudding user response:

The most pythonic way is to use a list comprehension:

a = ['cat', 'dog', 'ostritch']
replace_mapping = {'cat': 'sal',
                   'dog': 'fred',
                   'ostritch': 'martin'}
a = [replace_mapping.get(word, word) for word in a]
print(a)

Output:

['sal', 'fred', 'martin']
  • Related