Issues when sorting a list of string

Nauman Shahid

I currently have the following list of strings:

['0\t ***       *', '1\t    *     *', '2\t     *   *', '3\t      ***', 
 '-1\t            *', '-2\t             *', '-3\t              **']

So, I am trying to sort the list such that it becomes:

['3\t      ***', '2\t     *   *', '1\t    *     *', '0\t ***       *', 
'-1\t            *', '-2\t             *', '-3\t              **']

However, when I use:

new_list = sorted(new_list, reverse=True)

I get the following:

['3\t      ***', '2\t     *   *', '1\t    *     *', '0\t ***       *',
'-3\t              **', '-2\t             *', '-1\t            *']

How would I fix it so that it takes -3 into account rather than just - when sorting the strings in the list.

fferri

A list of strings gets sorted alphabetically.

You need to supply a key function, in order to split on the '\t' char, and parse the first field as integer:

>>> l=['0\t ***       *', '1\t    *     *', '2\t     *   *', '3\t      ***', '-1\t            *', '-2\t             *', '-3\t              **']
>>> l.sort(key=lambda x: int(x.split('\t')[0]), reverse=True)
>>> l
['3\t      ***', '2\t     *   *', '1\t    *     *', '0\t ***       *', '-1\t            *', '-2\t             *', '-3\t              **']

Note that instead of doing new_list = sorted(new_list, reverse=True) you can do in-place sort with new_list.sort(reverse=True).

Or, if you don't mind using third party packages, you can have a look at the natsort package, which seems to solve exactly this kind of problems.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related