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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With