Frank
Frank

Reputation: 66174

Subtract tuple of tuples from a tuple in Python?

I have a tuple of tuples:

nums = ((4, 5, 6), (5, 6, 7), (2, 3))

Now I want to create a similar structure in which each number is subtracted from a 'baseline' number. The baseline numbers for the tuples are:

baselines = (1, 0.5, 3)

So the structure I want would be:

# want: diffs = ((3, 4, 5), (4.5, 5.5, 6.5), (-1, 0))

where we have:

diffs[0] = [x - baselines[0] for x in nums[0]]
diffs[1] = [x - baselines[1] for x in nums[1]]
# etc.

How can I do this elegantly in Python?

Upvotes: 0

Views: 1805

Answers (2)

John La Rooy
John La Rooy

Reputation: 304147

>>> [[x-baselines[i] for x in nums[i]] for i in range(3)]
[[3, 4, 5], [4.5, 5.5, 6.5], [-1, 0]]

You can make it tuples like so

>>> tuple(tuple(x-baselines[i] for x in nums[i]) for i in range(3))
((3, 4, 5), (4.5, 5.5, 6.5), (-1, 0))

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Use zip with a generator expression:

In [66]: nums = ((4, 5, 6), (5, 6, 7), (2, 3))

In [67]: baselines = (1, 0.5, 3)

In [68]: tuple( tuple( val-y for val in x ) for x,y in zip (nums,baselines ))
Out[68]: ((3, 4, 5), (4.5, 5.5, 6.5), (-1, 0))

Upvotes: 3

Related Questions