pythonarraysnumpycomparisonrank

Python pairwise comparison of elements in a array or list


Let me elaborate my question using a simple example.I have a=[a1,a2,a3,a4], with all ai being a numerical value.

What I want to get is pairwise comparisons within 'a', such as I(a1>=a2), I(a1>=a3), I(a1>=a4), ,,,,I(a4>=a1), I(a4>=a2), I(a4>=a3), where I is a indicator function. So I used the following code.

res=[x>=y for x in a for y in a]

But it also gives the comparison results like I(a1>=a1),..,I(a4>=a4), which is always one. To get rid of these nuisance, I convert res into a numpy array and find the off diagonal elements.

res1=numpy.array(res)

This gives the result what I want, but I think there should be more efficient or simpler way to do pairwise comparison and extract the off diagonal element. Do you have any idea about this? Thanks in advance.


Solution

  • Perhaps you want:

     [x >= y for i,x in enumerate(a) for j,y in enumerate(a) if i != j]
    

    This will not compare any item against itself, but compare each of the others against each other.