Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list sorting dependant on if items are in another list

Say I have a list:

A = [1,2,3,4,5,6,7,8,9,0]

and a second list:

B = [3,6,9]

What is the best way to sort list A so that anything that matches an item in list B will appear at the beginning so that the result would be:

[3,6,9,1,2,4,5,7,8,0]
like image 860
Ashy Avatar asked May 16 '13 11:05

Ashy


4 Answers

>>> A = [1,2,3,4,5,6,7,8,9,0]
>>> B = [3,6,9]
>>> sorted(A,key=lambda e: e not in B)
[3, 6, 9, 1, 2, 4, 5, 7, 8, 0]

How this works:

sorted sorts an interable based on the result of key(element) for each element (the default value for key is None which results in it sorting based on the elements directly).

In our case the lambda lambda e: e not in B will return either True if e isn't in B, or False if e is in B. The element's with False's get sorted to the front, and you end up with your result. As demonstrated by:

>>> sorted([True,False,False])
[False, False, True]
like image 61
HennyH Avatar answered Oct 20 '22 03:10

HennyH


Many of these answers are using set logic explicitly. But Python has it built in. If, as you say, the order doesn't matter as long as the B parts come first, this will take care of the rest:

B = set(B)
list(B.intersection(A)) + list(set(A) - B)

This assumes that (as in your example) there are no duplicate values. If there are, use one of the list comprehension answers.

like image 28
kojiro Avatar answered Oct 20 '22 04:10

kojiro


>>> A = [1,2,3,4,5,6,7,8,9,0]
>>> B = [3,6,9]
>>> [i for i in B if i in A] + [i for i in A if i not in B]
[3, 6, 9, 1, 2, 4, 5, 7, 8, 0]
like image 2
defuz Avatar answered Oct 20 '22 04:10

defuz


>>> A = [1,2,3,4,5,6,7,8,9,0]
>>> B = [3,6,9]
>>> b = set(B)
>>> sorted(A, key=b.__contains__, reverse=True)
[3, 6, 9, 1, 2, 4, 5, 7, 8, 0]
like image 2
wim Avatar answered Oct 20 '22 03:10

wim