Python pairwise comparison of elements in a array or list
<p>Let me elaborate my question using a simple example.I have a=[a1,a2,a3,a4], with all ai being a numerical value. </p>

<p>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.</p>

<pre><code>res=[x&gt;=y for x in a for y in a]
</code></pre>

<p>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.</p>

<pre><code>res1=numpy.array(res)
</code></pre>

<p>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.</p>

<p>Why are you worried about the <code>a1&gt;=a1</code> comparison.  It may be pridictable, but skipping it might not be worth the extra work.</p>

<p>Make a list of 100 numbers</p>

<pre><code>In [17]: a=list(range(100))
</code></pre>

<p>Compare them with the simple double loop; producing a 10000 values (100*100)</p>

<pre><code>In [18]: len([x&gt;=y for x in a for y in a])
Out[18]: 10000
In [19]: timeit [x&gt;=y for x in a for y in a]
1000 loops, best of 3: 1.04 ms per loop
</code></pre>

<p>Now use <code>@Moinuddin Quadri's</code> enumerated loop to skip the 100 <code>eye</code> values:</p>

<pre><code>In [20]: len([x&gt;=y for i,x in enumerate(a) for j, y in enumerate(a) if i!=j])
Out[20]: 9900
In [21]: timeit [x&gt;=y for i,x in enumerate(a) for j, y in enumerate(a) if i!=j]
100 loops, best of 3: 2.12 ms per loop
</code></pre>

<p>It takes 2x longer.  Half the extra time is the enumerates, and half the <code>if</code>.</p>

<p>In this case working with numpy arrays is much faster, even when including the time to create the array.</p>

<pre><code>xa = np.array(x); Z = xa[:,None]&gt;=xa
</code></pre>

<p>But you can't get rid of the the diagonal values.  They will the <code>True</code>; they can be flipped to <code>False</code>, but why.  In a boolean array there are only 2 values.</p>

<p>The fastest solution is to write an indicator function that isn't bothered by these diagonal values.</p>

python arrays numpy comparison rank