3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I couldn't figure out how to account for the numbers.
1

If your first two char will always be either a number (e.g. -1) or a number and \ or \t (e.g. 2\), you can set a custom key and strip:

>>> sorted(i, reverse = True, key = lambda k: int(k[0:2].strip()))

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.