Thanos Smar
Thanos Smar

Reputation: 651

How to append a list using values from other list(maximum in the first must be minimum in the second)

a = [1 5 2 4 6 3]

I have this list. Is there a way to make a second corresponding list with the same number but 6 from a list must be 1 in the b list and 1 in a list must be 6 in b list .I want exactly this:

b = [6 2 5 3 1 4]

Upvotes: 0

Views: 33

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

Use zip of the sorted, and reversed-sorted list to create a reverse mapping from reversed-tuples:

>>> a = [1, 5, 2, 4, 6, 3]
>>> reverse_mapping = dict(zip(sorted(a), reversed(sorted(a))))

Creates the following mapping:

{1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}

Now use that to construct the new list:

>>> b = [reverse_mapping[item] for item in a]
>>> b
[6, 2, 5, 3, 1, 4]

This can be optimized if needed, I just kept it clear.

Upvotes: 2

Related Questions