I have lists such as:
mylist1 = ['alpha', 'green']
mylist2 = ['blue', 'alpha', 'red']
I want to sort these two lists by this custom ordered list: ['red','blue','green','alpha']
so that mylist1 = ['green', 'alpha']
and mylist2 = ['red','blue','alpha']
How can i do this in Python?
Custom Sorting With key= The key function takes in 1 value and returns 1 value, and the returned "proxy" value is used for the comparisons within the sort. For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest.
A custom list can correspond to a cell range, or you can enter the list in the Custom Lists dialog box. Note: A custom list can only contain text or text that is mixed with numbers. For a custom list that contains numbers only, such as 0 through 100, you must first create a list of numbers that is formatted as text.
Custom Sort allows you to create your order in which you want to sort the data. Sometimes you do not prefer the existing order and you want to sort it in a different order, then you can always choose to Custom Sort your data. To do Custom Sorting, you just need to create a Custom List.
Demonstration:
>>> mylist1 = ['alpha', 'green']
>>> mylist2 = ['blue', 'alpha', 'red']
>>> sort_order = ['red', 'blue', 'green', 'alpha']
>>> mylist1.sort(key=sort_order.index)
>>> mylist1
['green', 'alpha']
>>> mylist2.sort(key=sort_order.index)
>>> mylist2
['red', 'blue', 'alpha']
Explanation:
The key
parameter in list.sort
causes the list to determine the order by comparing key(element)
instead of element
. For example, to do case-insensitive sort, you can pass a key
function which makes the string lowercase. The lowercase elements are compared, but the original elements are preserved:
>>> x = ["age", "Bonkers", "cheese"]
>>> x.sort()
>>> x
['Bonkers', 'age', 'cheese']
>>> str.lower("Bonkers")
'bonkers'
>>> x.sort(key=str.lower)
>>> x
['age', 'Bonkers', 'cheese']
Using sort_order.index
for the key uses the index that element has in the sort_order
list to determine the order instead of the element itself. So 'red'
uses 0
, 'blue'
uses 1
, etc... the result is that the list to be sorted gets sorted according to where each element is in sort_order
.
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