Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementwise operations over tuples in Python

Are there any built-in functions that allow elementwise operations over tuples in Python 3? If not, what is the "pythonic" way to perform these operations?

Example: I want to take the percent difference between a and b and compare them to some threshold th.

>>> a = (1, 2, 4)
>>> b = (1.1, 2.1, 4.1)
>>> # compute pd = 100*abs(a-b)/a = (10.0, 5.0, 2.5)
>>> th = 3
>>> # test threshold: pd < th => (False, False, True)
like image 454
astay13 Avatar asked Aug 24 '12 16:08

astay13


People also ask

How do tuples add element wise?

To add two tuples element-wise:Use the zip function to get an iterable of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, pass the tuple to the sum() function.


1 Answers

There is no builtin way, but there is a pretty simple way:

[f(aItem, bItem) for aItem, bItem in zip(a, b)]

. . . where f is the function you want to apply elementwise. For your case:

[100*abs(aItem - bItem)/aItem < 3 for aItem, bItem in zip(a, b)]

If you find yourself doing this a lot, especially with long tuples, you might want to look at Numpy, which provides a full-featured system of vector operations in which many common vector functions (basic operations, trig functions, etc.) apply elementwise.

like image 82
BrenBarn Avatar answered Oct 13 '22 16:10

BrenBarn