[SOLVED] Arranging a list based on the distance of its elements from a given value

Issue

Let’s assume we have a list like the following
[2.3, 1.02, 1.99, 0.99, 0.089, 0, 1.1, -1.1, -2.1]

We want to arrange the elements of this list based on their distance from target value equal to 1 in the following manner:
[0.99, 1.02, 1.1, 0.089, 1.99, 0, 2.3, -1.1, -2.1]

How to do that in python in one or two lines?

Solution

python solution

Use sorted with the absolute distance to target as key:

L = [2.3, 1.02, 1.99, 0.99, 0.089, 0, 1.1, -1.1, -2.1]
target = 1

out = sorted(L, key=lambda x: abs(x-target))

output: [0.99, 1.02, 1.1, 0.089, 1.99, 0.0, 2.3, -1.1, -2.1]

numpy solution

Compute the absolute distance and use numpy.argsort:

L = [2.3, 1.02, 1.99, 0.99, 0.089, 0, 1.1, -1.1, -2.1]
target = 1

import numpy as np
a = np.array(L)
out = a[np.argsort(abs(a-target))].tolist()

output: [0.99, 1.02, 1.1, 0.089, 1.99, 0.0, 2.3, -1.1, -2.1]

Answered By – mozway

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *