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>You may achieve that by using:</p>

<pre><code>[x &gt;= y for i,x in enumerate(a) for j,y in enumerate(a) if i != j]
</code></pre>

<p><strong><em>Issue with your code</em></strong>:</p>

<p>You are iterating in over list twice. If you convert your <code>comprehension</code> to <code>loop</code>, it will work like:</p>

<pre><code>for x in a:
    for y in a:
        x&gt;=y # which is your condition
</code></pre>

<p>Hence, it the the order of execution is as: (a1, a1), (a1, a2), ... , (a2, a1), (a2, a2), ... , (a4, a4)</p>

python arrays numpy comparison rank