345243lkj 345243lkj - 3 months ago 6
Python Question

Combining Indices of Two Sorted Lists to Form a Third SuperSorted List

I have two lists

['AAPL', 'MMM', 'AMAT']
and
['AMAT', 'AAPL', 'MMM']
and I want to create a third list based on the positions of each string in its respective list.

For example:
AAPL
ranks 1st + 2nd = total 3,
MMM
ranks 2nd and 3rd = total 5,
AMAT
ranks 1st and 3rd = total 4.

Final list would be (by decreasing cumulative position)
['AAPL', 'AMAT', 'MMM']
.

I don't even know where to begin with this.

Answer

Just take one and do sort it by cumulative position.

>>> a, b = ['AAPL', 'MMM', 'AMAT'], ['AMAT', 'AAPL', 'MMM']
>>> sorted(a, key=lambda x: a.index(x) + b.index(x))
['AAPL', 'AMAT', 'MMM']
Comments