What is the pythonic way to get the number of times list1 [i] <list2 [i] and vice versa
I have two lists with values, the expected result is a tuple (a,b), where ais the number of values of i, which list1[i] < list2[i], and bis the number of values of i, where list1[i] > list2[i](equalities are not taken into account at all).
I have this solution and it works fine:
x = (0,0)
for i in range(len(J48)):
if J48[i] < useAllAttributes7NN[i]:
x = (x[0]+1,x[1])
elif J48[i] > useAllAttributes7NN[i]:
x = (x[0], x[1]+1)
However, I am trying to improve my python skills, and this seems like a very non-pythonic way to achieve it.
What is the pythonic way to achieve the same result?
FYI , this is done to achieve the required input for binom_test(), which tries to prove two algorithms: not statistically identical.
I do not believe that this information has any additional value for a specific issue.
One way is to create a set of points and then add them.
scores = [ (a < b, a > b) for (a, b) in zip(J48, useAllAttributes7nn) ]
x = (sum( a for (a, _) in scores ), sum( b for (_, b) in scores ))
// Or, as per @agf suggestion (though I prefer comprehensions to map)...
x = [ sum(s) for s in zip(*scores) ]
Another is to fix them once, and then calculate the points separately:
zipped = zip(J48, useAllAttributes7nn)
x = (sum( a < b for (a, b) in zipped ), sum( a > b for (a, b) in zipped ))
Note that this does not work in Python 3 (thanks @Darthfett).
:
list1 = range(10)
list2 = reversed(range(10))
x = [0, 0]
for a, b in zip(list1, list2):
x[0] += 1 if a < b else 0
x[1] += 1 if a > b else 0
x = tuple(x)
:
(5, 5)
zip()- The best way to iterate over two lists at once. If you're using Python 2.x, you can use itertools.izipfor performance reasons (he is lazy as 3.x the Python zip().
It is also easier to work on a list until you stop modifying it, since the list has been changed.
Edit:
Python 3 compatible version of versions using cmp:
def add_tuples(*args):
return tuple(sum(z) for z in zip(*args))
add_tuples(*[(1, 0) if a < b else ((0, 1) if a > b else (0, 0)) for a, b in zip(list1, list2)])