Are there any built-in functions that allow elementary processing of tuples in Python 3? If not, what is the "pythonic" way of performing these operations?
Example. I want to take the percentage difference between aand band compare them with a certain threshold th.
a
b
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)
display function
>>> a = (1, 2, 4) >>> b = (1.1, 2.1, 4.1) >>> map(lambda a,b: 100*abs(a-b)/a < 3, a, b) [False, False, True]
EDIT
of course, instead of a map, you can use lists, for example, BrenBarn did http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions
EDIT 2 zip removed, thanks DSM indicate no zip needed
, :
[f(aItem, bItem) for aItem, bItem in zip(a, b)]
., f - , -. :
f
[100*abs(aItem - bItem)/aItem < 3 for aItem, bItem in zip(a, b)]
, , , Numpy, , ( , -, ..) -.
Numpy
NumPy?
import numpy as np a = np.array([1,2,4]) b = np.array([1.1, 2.1, 4.1]) pd = 100*abs(a-b)/a # result: array([ 10. , 5. , 2.5]) th = 3 pd < th # result: array([False, False, True], dtype=bool)
, , Python (map? reduce?), ( , ) :
[100*abs(j-b[i])/j < 3 for i,j in enumerate(a)] [False, False, True]
@delnan , / :
[True if 100*abs(j-b[i])/j < 3 else False for i,j in enumerate(a)]
, Pythonic :
a = (1, 2, 4) b = (1.1, 2.1, 4.1)
a = (1, 2, 4)
b = (1.1, 2.1, 4.1)
:
TEST = [100*abs(a[i]-b[i])/a[i] > th for i in range(len(A))]
def pctError(observed, expected): return (observed-expected)/expected * 100.0 a = (1, 2, 4) b = (1.1, 2.1, 4.1) th = 3 pctErrors = map(lambda t:pctError(*t), zip(a,b)) # returns [-9.091, -4.76, -2.44] map(lambda x: x < th, pctErrors) [x < th for x in pctErrors] # both return [True, True, True] # or if you always need absolute % errors map(lambda x: abs(x) < th, pctErrors) [abs(x) < th for x in pctErrors] # both return [False, False, True]