Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sort order of list

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?

like image 334
mensah Avatar asked Aug 23 '13 17:08

mensah


People also ask

How do you sort a list in custom order 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.

When you say sort by custom list what is a custom list in sorting?

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.

What is custom sort order in Excel?

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.


1 Answers

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.

like image 107
Claudiu Avatar answered Sep 18 '22 00:09

Claudiu