Max
Max

Reputation: 8045

how to rebuild a tuple with some modification?

For example, I got a tuple

a = ('chicken', 1, 'lemon', 'watermelon', 'camel')

I want to build a new tuple b from a but change a little bit

d = {0: 'apple', 1: 'banana', 2: 'lemon', 3: 'watermelon'}

b = (a[0], d[a[1]], a[2], a[3], a[4])

another way to do it

b = list(a)
b[1] = d[b[1]]
b = tuple(b)

All of them work, but look silly.

Is there another elegant way to do this job? or are there some skills to modify the original tuple?

Upvotes: 1

Views: 213

Answers (2)

Mats Kindahl
Mats Kindahl

Reputation: 2075

I don't know what you mean by "elegant", but if you want something more generic that just replaces elements in the 'a' tuple that have a key in 'd', you can use a generator expression and do something like:

>>> a
('chicken', 1, 'lemon', 'watermelon', 'camel')
>>> d
{0: 'apple', 1: 'banana', 2: 'lemon', 3: 'watermelon'}
>>> tuple(d[x] if x in d else x for x in a)
('chicken', 'banana', 'lemon', 'watermelon', 'camel')

It constructs a new tuple, since tuples are immutable.

Upvotes: 1

RocketDonkey
RocketDonkey

Reputation: 37269

This is a bit inefficient in comparison to yours because it does a check on every item, but the general idea is that it looks at each item in your a, checks for a matching key in d and if it finds one, returns the value at that key. If no key is found, the original item is returned:

In [1]: a = ('chicken',1,'lemon','watermelon','camel')

In [2]: d = {0:'apple',1:'banana',2:'lemon',3:'watermelon'}

In [3]: b = tuple(d.get(x, x) for x in a)

In [4]: b
Out[4]: ('chicken', 'banana', 'lemon', 'watermelon', 'camel')

In [5]: type(b)
Out[5]: <type 'tuple'>

Upvotes: 4

Related Questions