简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM