Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of strings and place numbers after letters in python

I have a list of strings that I want to sort.

By default, letters have a larger value than numbers (or string numbers), which places them last in a sorted list.

>>> 'a' > '1'
True
>>> 'a' > 1
True

I want to be able to place all the strings that begins with a number at the bottom of the list.

Example:

Unsorted list:

['big', 'apple', '42nd street', '25th of May', 'subway']

Python's default sorting:

['25th of May', '42nd street', 'apple', 'big', 'subway']

Requested sorting:

['apple', 'big', 'subway', '25th of May', '42nd street']
like image 264
Nir Avatar asked Jul 08 '14 05:07

Nir


1 Answers

>>> a = ['big', 'apple', '42nd street', '25th of May', 'subway']
>>> sorted(a, key=lambda x: (x[0].isdigit(), x))
['apple', 'big', 'subway', '25th of May', '42nd street']

Python's sort functions take an optional key parameter, allowing you to specify a function that gets applied before sorting. Tuples are sorted by their first element, and then their second, and so on.

You can read more about sorting here.

like image 107
grc Avatar answered Sep 24 '22 05:09

grc