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]
>>> 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]
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.
>>> 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]
>>> 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]
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