Custom List Sort Order

I have lists, for example:

mylist1 = ['alpha', 'green'] mylist2 = ['blue', 'alpha', 'red'] 

I want to sort these two lists using this ordered list: ['red','blue','green','alpha']

so mylist1 = ['green', 'alpha'] and mylist2 = ['red','blue','alpha']

How can I do this in Python?

+4
source share
3 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 make case-insensitive sorting, you can pass a key function that makes a string lowercase. Lower case 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 the 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 sorted list is sorted according to where each item is in sort_order .

+10
source

Use the index as a key.

 key=lambda x: customlist.index(x) 
+4
source

You can use:

 >>> a = ['red','blue','green','alpha'] >>> b = ['alpha', 'green'] >>> filter(set(b).__contains__, a) ['green', 'alpha'] 

Instead of sorting the list in order, we include only the elements from the already ordered list a , which are present in the source list b .

You can write this as [el for el in a if el in b] and optionally have b as a collection if you want.

Of course, if you really wanted to sort it, then you should probably create an index search, and not potentially repeat it several times (continuing to produce .index ):

 order = {v:i for i,v in enumerate(a)} b.sort(key=order.get) 
+1
source

Source: https://habr.com/ru/post/1498645/


All Articles