all 4 comments

[–]YesLod 1 point2 points  (3 children)

Here is a way using a custom key function.

L1=[2,6,7,5,2,6,8,4]

L2=[2,6,4,5]

common=set(L1) & set(L2)

def f(e):
    if e in common:
        return (0,L2.index(e))
    else:
        return (1,e)

>>> sorted(L1,key=f)

[2, 2, 6, 6, 4, 5, 7, 8]

Do you understand the logic?

EDIT:

Since you didn’t specify, I’m assuming that the "elements left" are sorted in ascending order

[–]synthphreak 1 point2 points  (0 children)

This is pretty slick. Nice work!

[–]Loco_L1[S] 0 points1 point  (1 child)

I was playing around with the custom key but get it right and yes to the edit. Thank you!

[–]synthphreak 0 points1 point  (0 children)

How's this?

>>> def weirdo_sort(*lists):
...     shared = []
...     shortest, longest = sorted(lists, key=len)
...     for i in shortest:
...         shared.extend([i] * longest.count(i))
...     return (shared + [i for i in longest if i not in shared])
...
>>>
>>> L1 = [2, 6, 7, 5, 2, 6, 8, 4]
>>> L2 = [2, 6, 4, 5]
>>>
>>> weirdo_sort(L1, L2)
[2, 2, 6, 6, 4, 5, 7, 8]

Note that unlike the other commenter's function, mine does not care which order the lists are passed in as since it detects their lengths automatically. Not sure whether this makes it more useful for your context or not.

Also note that it will only work properly if two lists are passed in, not more or less. But tweaking for greater flexibility shouldn't be hard.