How to Sort Python List in Custom Order
In Python, the sorted() function can be used to sort in a specified order.
When sorting, you can pass a key parameter to specify the criteria for sorting. The key parameter takes a function that returns a value to be used for comparison. For example, if you want to sort based on the length of strings, you can set the key parameter to the len function.
Here is an example code sorted in the specified order:
fruits = ['apple', 'banana', 'cherry', 'date']
def custom_order(item):
order = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4}
return order[item]
sorted_fruits = sorted(fruits, key=custom_order)
print(sorted_fruits)
In the above example, a custom_order function is defined which returns the index of fruits in a custom order. By setting the key parameter to the custom_order function, the sorted() function will sort according to the custom order. The output will be sorted based on the custom order.