Given the following list of tokens:
a = ['heyyo', 'how', 'ale', 'yiou']
And a list of tuples:
b = [('yiou', 'you'), ('heyyo', 'hello')]
How can I replace the elements of the list a
considering the elements of the list b
? For example, the expected output would be:
['hello', 'how', 'ale', 'you']
This is due to list b
has as a replacement:yiou
for you
and heyyo
for hello
. How to make the above replacement securing the same original order of list a
?
You can create a dict on b
and then search each item of a
in dct_b
with dict.get()
. If exist return value
base key
and if doesn't exist return the item.
dct_b = dict(b)
res = [dct_b.get(item, item) for item in a]
print(res)
Output:
['hello', 'how', 'ale', 'you']