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']
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With