Lostsoul
Lostsoul

Reputation: 25999

How can I order a list based on another lists order?

I have a strange problem so I'll just demo it for you to make it easier to understand. I have two lists:

>>> a = [1, 2, 20, 6, 210]
>>> b = [20, 6, 1]

The result I'm looking for is 3 (position of last matching item in list a based on matches in b)

b always has less data as it contains all duplicates of list a. I want to know what item in B matches the furthest in list a. So in this example, it would be 6 as 6 is furthest in the list of A.

Is there an easy way to do this - my initial approach is a nested loop but I suspect there's a simpler approach?

Upvotes: 0

Views: 97

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155418

The simplest (if not necessarily most efficient) code is just:

 max(b, key=a.index)

or if you want the whole list sorted, not just the maximum value as described, one of:

b.sort(key=a.index)

or

sorted(b, key=a.index)

If duplicates in the reference list are a possibility and you need to get the last index of a value, replace index with one of these simulations of rindex.

Update: Addressing your requirement for getting the position, not the value, there is an alternative way to solve this that would involve less work. It's basically a modification of one of the better solutions to emulating rindex:

bset = frozenset(b)
last_a_index = len(a) - next(i for i, x in enumerate(reversed(a), 1) if x in bset)

This gets the work down to O(m + n) (vs. O(m * n) for other solutions) and it short-circuits the loop over a; it scans in reverse until it finds a value in b then immediately produces the index. It can trivially be extended to produce the value with a[last_a_index], since it doesn't really matter where it was found in b. More complex code, but faster, particularly if a/b might be huge.

Upvotes: 4

superb rain
superb rain

Reputation: 5521

Since you asked for the position:

>>> max(map(a.index, b))
3

Upvotes: 2

Related Questions