Abhishek dot py Abhishek dot py - 1 month ago 3x
Python Question

Sort list with according to uneven value

I am creating a script for a library, that sorts authors in decending order of their Avg rating.

Below is my list: ( It have author name + < space > + Avg Rating )

['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']

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

for line in rate_order:
sort_list.append(line.split(' '))
print sorted(sort_list, key=itemgetter(2))

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?


Use rsplit

>>> help(''.rsplit)
Help on built-in function rsplit:

    S.rsplit([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string, starting at the end of the string and working
    to the front.  If maxsplit is given, at most maxsplit splits are
    done. If sep is not specified or is None, any whitespace string
    is a separator.

>>> 'George R.R. Martin 5.0'.rsplit(' ', 1)
['George R.R. Martin', '5.0']

Another way to grab the last item of the split is to use an index of -1:

>>> 'George R.R. Martin 5.0'.split()[-1]

If your list is called author_ratings you can sort it in-place by doing

author_ratings.sort(key=(lambda(s): float(s.rsplit(' ', 1)[1])), reverse=True)