简体   繁体   中英

How to we customise a sorting function based on the first alphabet of the word in a list?

Write a function that takes in a list of strings and return a list with the strings in sorted order, except group all the strings that begin with 'H' first. For example, providing the following input list:

['Bougainvillea', 'Orchids', 'Hibiscus', 'Frangipani', 'Honeysuckle']

will return the following output list:

['Hibiscus', 'Honeysuckle', 'Bougainvillea', 'Frangipani', 'Orchids']

You can provide a key function to specify sorting order. For example, you can do this:

>>> the_list = ['Bougainvillea', 'Orchids', 'Hibiscus', 'Frangipani', 'Honeysuckle']
>>> sorted(the_list, key=lambda item: (0 if item.startswith("H") else 1, item))
['Hibiscus', 'Honeysuckle', 'Bougainvillea', 'Frangipani', 'Orchids']

Your key function can produce anything that's sortable. This example used a tuple, and tuples are sorted elementwise (ties in the_tuple[0] are broken by the_tuple[1] and so on)

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