title: Efficient method to calculate the rank vector of a list in Python
body: <p>I'm looking for an efficient way to calculate the rank vector of a list in Python, similar to R's <code>rank</code> function. In a simple list with no ties between the elements, element <em>i</em> of the rank vector of a list <code>l</code> should be <em>x</em> if and only if <code>l[i]</code> is the <em>x</em>-th element in the sorted list. This is simple so far, the following code snippet does the trick:</p>
  
  <pre><code>def rank_simple(vector):
      return sorted(range(len(vector)), key=vector.__getitem__)
  </code></pre>
  
  <p>Things get complicated, however, if the original list has ties (i.e. multiple elements with the same value). In that case, all the elements having the same value should have the same rank, which is the average of their ranks obtained using the naive method above. So, for instance, if I have <code>[1, 2, 3, 3, 3, 4, 5]</code>, the naive ranking gives me <code>[0, 1, 2, 3, 4, 5, 6]</code>, but what I would like to have is <code>[0, 1, 3, 3, 3, 5, 6]</code>. Which one would be the most efficient way to do this in Python?</p>
  
  <hr>
  
  <p>Footnote: I don't know if NumPy already has a method to achieve this or not; if it does, please let me know, but I would be interested in a pure Python solution anyway as I'm developing a tool which should work without NumPy as well.</p>