Anonymous_learner
Anonymous_learner

Reputation: 1

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

Upvotes: 0

Views: 50

Answers (1)

Chris Warrick
Chris Warrick

Reputation: 1629

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)

Upvotes: 2

Related Questions