Rcoding
Rcoding

Reputation: 357

Multiple string substitution for tuples in Python

I want to substitute multiple string elements in tuples with replace set.

from itertools import chain

old = [('Jack','Mike'),('Rosa','Mike'),('Pete','Jake'),('Beth','Jake')]
uniquelist = list(dict.fromkeys([ i for i in chain(*old)]))
replaceset = [("a" + str(new),old) for new,old in enumerate(uniquelist)]

replaceset is:

[('a0', 'Jack'), ('a1', 'Mike'), ('a2', 'Rosa'), ('a3', 'Pete'), ('a4', 'Jake'), ('a5', 'Beth')]

This is the output I want from old.

[('a0','a1'),('a2','a1'),('a3','a4'),('a5','a4')]

Is there any way to deal with this?

Upvotes: 0

Views: 64

Answers (1)

Ma0
Ma0

Reputation: 15204

I am going to assume here that you are working with Python 3.7+ and that maintaining order is important to you.

Just convert replaceset into a dict and recreate old with a list-comprehension:

from itertools import chain

old = [('Jack','Mike'),('Rosa','Mike'),('Pete','Jake'),('Beth','Jake')]
uniquelist = list(dict.fromkeys([ i for i in chain(*old)]))
#replaceset = [("a" + str(new),old) for new,old in enumerate(uniquelist)]
replaceset = {old:"a" + str(new) for new, old in enumerate(uniquelist)}

res = [tuple(replaceset[name] for name in sub) for sub in old]
print(res)  # [('a0', 'a1'), ('a2', 'a1'), ('a3', 'a4'), ('a5', 'a4')]

As a sidenote,

uniquelist = dict.fromkeys(chain(*old))

would also work and make you more efficient too.

Upvotes: 2

Related Questions