Sort list with according to uneven value
<p>I am creating a script for a library, that sorts authors in decending order of their Avg rating.</p>

<p>Below is my list:  ( It have author name + &lt; space > + Avg Rating )</p>

<pre><code>['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt Pattanaik 4.42', 'George R.R. Martin 5.0', 'Dan Brown 5.0', 'Katherine Applegate 3.0', 'Eoin Colfer 4.25', 'Arthur Conan Doyle 5.0', 'Clive Cussler 4.66', 'Stephen King 3.66', 'Douglas Preston 5.0']
</code></pre>

<p>Below is what I tried: ( I split values with space, and appended in a new list, then sorted with third value, that is rating.</p>

<pre><code>for line in rate_order:
    sort_list.append(line.split(' '))
print sorted(sort_list, key=itemgetter(2))
</code></pre>

<p>The issue is that some author name has three spaces in their name, so the third value is not rating. Can there is better ( or cleaner ) way?</p>

<p>You could split at spaces, and then take the floating-point value of the last component. Here is the whole thing as a one-liner:</p>

<pre><code>&gt;&gt;&gt; print sorted(rate_order, key=lambda r:float(r.split(' ')[-1]))
['Katherine Applegate 3.0', 'Stephen King 3.66', 'Eoin Colfer 4.25', 'J.K. Rowling 4.36', 'Devdutt Pattanaik 4.42', 'Jeffrey Archer 4.62', 'Sidney Sheldon 4.63', 'Clive Cussler 4.66', 'Michael Crichton 4.71', 'Narendra Kohli 4.9', 'George R.R. Martin 5.0', 'Dan Brown 5.0', 'Arthur Conan Doyle 5.0', 'Douglas Preston 5.0']
</code></pre>

<p>Note that the <code>[-1]</code> index extracts the <em>last</em> element (the first starting from the end).</p>

python python-2.7